QGIS API Documentation 4.3.0-Master (91d4a333d5d)
Loading...
Searching...
No Matches
qgsfillsymbollayer.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgsfillsymbollayer.cpp
3 ---------------------
4 begin : November 2009
5 copyright : (C) 2009 by Martin Dobias
6 email : wonder dot sk at gmail dot com
7 ***************************************************************************
8 * *
9 * This program is free software; you can redistribute it and/or modify *
10 * it under the terms of the GNU General Public License as published by *
11 * the Free Software Foundation; either version 2 of the License, or *
12 * (at your option) any later version. *
13 * *
14 ***************************************************************************/
15
16#include "qgsfillsymbollayer.h"
17
18#include <random>
19
20#include "qgsapplication.h"
21#include "qgscolorramp.h"
22#include "qgscolorrampimpl.h"
23#include "qgscolorutils.h"
24#include "qgsdatadefinedutils.h"
25#include "qgsdxfexport.h"
27#include "qgsfeedback.h"
28#include "qgsfileutils.h"
29#include "qgsgeometry.h"
30#include "qgsgeometryengine.h"
31#include "qgsimagecache.h"
32#include "qgsimageoperation.h"
33#include "qgslinestring.h"
34#include "qgslinesymbol.h"
35#include "qgslinesymbollayer.h"
36#include "qgsmarkersymbol.h"
37#include "qgsmessagelog.h"
38#include "qgspainting.h"
39#include "qgspolygon.h"
40#include "qgsproject.h"
41#include "qgsrendercontext.h"
42#include "qgssldexportcontext.h"
43#include "qgssvgcache.h"
44#include "qgssymbol.h"
45#include "qgssymbollayerutils.h"
46#include "qgsunittypes.h"
47
48#include <QDomDocument>
49#include <QDomElement>
50#include <QFile>
51#include <QPagedPaintDevice>
52#include <QPainter>
53#include <QString>
54#include <QSvgRenderer>
55#include <QtMath>
56
57using namespace Qt::StringLiterals;
58
59QgsSimpleFillSymbolLayer::QgsSimpleFillSymbolLayer( const QColor &color, Qt::BrushStyle style, const QColor &strokeColor, Qt::PenStyle strokeStyle, double strokeWidth, Qt::PenJoinStyle penJoinStyle )
60 : mBrushStyle( style )
65{
66 mColor = color;
67}
68
70
76
78{
80 if ( mOffsetUnit != unit )
81 {
83 }
84 return unit;
85}
86
94
100
109
110void QgsSimpleFillSymbolLayer::applyDataDefinedSymbology( QgsSymbolRenderContext &context, QBrush &brush, QPen &pen, QPen &selPen )
111{
112 if ( !dataDefinedProperties().hasActiveProperties() )
113 return; // shortcut
114
115 bool ok;
116
118 {
121 fillColor.setAlphaF( context.opacity() * fillColor.alphaF() );
122 brush.setColor( fillColor );
123 }
125 {
128 if ( !QgsVariantUtils::isNull( exprVal ) )
129 brush.setStyle( QgsSymbolLayerUtils::decodeBrushStyle( exprVal.toString() ) );
130 }
132 {
135 penColor.setAlphaF( context.opacity() * penColor.alphaF() );
136 pen.setColor( penColor );
137 }
139 {
142 if ( !QgsVariantUtils::isNull( exprVal ) )
143 {
144 double width = exprVal.toDouble( &ok );
145 if ( ok )
146 {
148 pen.setWidthF( width );
149 selPen.setWidthF( width );
150 }
151 }
152 }
154 {
156 QString style = mDataDefinedProperties.valueAsString( QgsSymbolLayer::Property::StrokeStyle, context.renderContext().expressionContext(), QString(), &ok );
157 if ( ok )
158 {
159 pen.setStyle( QgsSymbolLayerUtils::decodePenStyle( style ) );
160 selPen.setStyle( QgsSymbolLayerUtils::decodePenStyle( style ) );
161 }
162 }
164 {
166 QString style = mDataDefinedProperties.valueAsString( QgsSymbolLayer::Property::JoinStyle, context.renderContext().expressionContext(), QString(), &ok );
167 if ( ok )
168 {
169 pen.setJoinStyle( QgsSymbolLayerUtils::decodePenJoinStyle( style ) );
170 selPen.setJoinStyle( QgsSymbolLayerUtils::decodePenJoinStyle( style ) );
171 }
172 }
173}
174
175
176std::unique_ptr<QgsSymbolLayer> QgsSimpleFillSymbolLayer::create( const QVariantMap &props )
177{
179 Qt::BrushStyle style = DEFAULT_SIMPLEFILL_STYLE;
184 QPointF offset;
185
186 if ( props.contains( u"color"_s ) )
187 color = QgsColorUtils::colorFromString( props[u"color"_s].toString() );
188 if ( props.contains( u"style"_s ) )
189 style = QgsSymbolLayerUtils::decodeBrushStyle( props[u"style"_s].toString() );
190 if ( props.contains( u"color_border"_s ) )
191 {
192 //pre 2.5 projects used "color_border"
193 strokeColor = QgsColorUtils::colorFromString( props[u"color_border"_s].toString() );
194 }
195 else if ( props.contains( u"outline_color"_s ) )
196 {
197 strokeColor = QgsColorUtils::colorFromString( props[u"outline_color"_s].toString() );
198 }
199 else if ( props.contains( u"line_color"_s ) )
200 {
201 strokeColor = QgsColorUtils::colorFromString( props[u"line_color"_s].toString() );
202 }
203
204 if ( props.contains( u"style_border"_s ) )
205 {
206 //pre 2.5 projects used "style_border"
207 strokeStyle = QgsSymbolLayerUtils::decodePenStyle( props[u"style_border"_s].toString() );
208 }
209 else if ( props.contains( u"outline_style"_s ) )
210 {
211 strokeStyle = QgsSymbolLayerUtils::decodePenStyle( props[u"outline_style"_s].toString() );
212 }
213 else if ( props.contains( u"line_style"_s ) )
214 {
215 strokeStyle = QgsSymbolLayerUtils::decodePenStyle( props[u"line_style"_s].toString() );
216 }
217 if ( props.contains( u"width_border"_s ) )
218 {
219 //pre 2.5 projects used "width_border"
220 strokeWidth = props[u"width_border"_s].toDouble();
221 }
222 else if ( props.contains( u"outline_width"_s ) )
223 {
224 strokeWidth = props[u"outline_width"_s].toDouble();
225 }
226 else if ( props.contains( u"line_width"_s ) )
227 {
228 strokeWidth = props[u"line_width"_s].toDouble();
229 }
230 if ( props.contains( u"offset"_s ) )
231 offset = QgsSymbolLayerUtils::decodePoint( props[u"offset"_s].toString() );
232 if ( props.contains( u"joinstyle"_s ) )
233 penJoinStyle = QgsSymbolLayerUtils::decodePenJoinStyle( props[u"joinstyle"_s].toString() );
234
235 auto sl = std::make_unique< QgsSimpleFillSymbolLayer >( color, style, strokeColor, strokeStyle, strokeWidth, penJoinStyle );
236 sl->setOffset( offset );
237 if ( props.contains( u"border_width_unit"_s ) )
238 {
239 sl->setStrokeWidthUnit( QgsUnitTypes::decodeRenderUnit( props[u"border_width_unit"_s].toString() ) );
240 }
241 else if ( props.contains( u"outline_width_unit"_s ) )
242 {
243 sl->setStrokeWidthUnit( QgsUnitTypes::decodeRenderUnit( props[u"outline_width_unit"_s].toString() ) );
244 }
245 else if ( props.contains( u"line_width_unit"_s ) )
246 {
247 sl->setStrokeWidthUnit( QgsUnitTypes::decodeRenderUnit( props[u"line_width_unit"_s].toString() ) );
248 }
249 if ( props.contains( u"offset_unit"_s ) )
250 sl->setOffsetUnit( QgsUnitTypes::decodeRenderUnit( props[u"offset_unit"_s].toString() ) );
251
252 if ( props.contains( u"border_width_map_unit_scale"_s ) )
253 sl->setStrokeWidthMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( props[u"border_width_map_unit_scale"_s].toString() ) );
254 if ( props.contains( u"offset_map_unit_scale"_s ) )
255 sl->setOffsetMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( props[u"offset_map_unit_scale"_s].toString() ) );
256
257 sl->restoreOldDataDefinedProperties( props );
258
259 return sl;
260}
261
262
264{
265 return u"SimpleFill"_s;
266}
267
272
274{
275 QColor fillColor = mColor;
276 fillColor.setAlphaF( context.opacity() * mColor.alphaF() );
277 mBrush = QBrush( fillColor, mBrushStyle );
278
279 QColor selColor = context.renderContext().selectionColor();
280 QColor selPenColor = selColor == mColor ? selColor : mStrokeColor;
281 if ( !SELECTION_IS_OPAQUE )
282 selColor.setAlphaF( context.opacity() );
283 mSelBrush = QBrush( selColor );
284 // N.B. unless a "selection line color" is implemented in addition to the "selection color" option
285 // this would mean symbols with "no fill" look the same whether or not they are selected
286 if ( SELECT_FILL_STYLE )
287 mSelBrush.setStyle( mBrushStyle );
288
289 QColor strokeColor = mStrokeColor;
290 strokeColor.setAlphaF( context.opacity() * mStrokeColor.alphaF() );
291 mPen = QPen( strokeColor );
292 mSelPen = QPen( selPenColor );
293 mPen.setStyle( mStrokeStyle );
295 mPen.setJoinStyle( mPenJoinStyle );
296}
297
299{
300 Q_UNUSED( context )
301}
302
303void QgsSimpleFillSymbolLayer::renderPolygon( const QPolygonF &points, const QVector<QPolygonF> *rings, QgsSymbolRenderContext &context )
304{
305 QPainter *p = context.renderContext().painter();
306 if ( !p )
307 {
308 return;
309 }
310
311 QColor fillColor = mColor;
312 fillColor.setAlphaF( context.opacity() * mColor.alphaF() );
313 mBrush.setColor( fillColor );
314 QColor strokeColor = mStrokeColor;
315 strokeColor.setAlphaF( context.opacity() * mStrokeColor.alphaF() );
316 mPen.setColor( strokeColor );
317
318 applyDataDefinedSymbology( context, mBrush, mPen, mSelPen );
319
320 QPointF offset = mOffset;
321
323 {
325 const QVariant val = mDataDefinedProperties.value( QgsSymbolLayer::Property::Offset, context.renderContext().expressionContext(), QString() );
326 bool ok = false;
327 const QPointF res = QgsSymbolLayerUtils::toPoint( val, &ok );
328 if ( ok )
329 offset = res;
330 }
331
332 if ( !offset.isNull() )
333 {
336 p->translate( offset );
337 }
338
339 const bool useSelectedColor = shouldRenderUsingSelectionColor( context );
340
341 if ( mBrush.style() == Qt::SolidPattern || mBrush.style() == Qt::NoBrush || !dynamic_cast<QPagedPaintDevice *>( p->device() ) )
342 {
343 p->setPen( useSelectedColor ? mSelPen : mPen );
344 p->setBrush( useSelectedColor ? mSelBrush : mBrush );
345 _renderPolygon( p, points, rings, context );
346 }
347 else
348 {
349 // workaround upstream issue https://github.com/qgis/QGIS/issues/36580
350 // when a non-solid brush is set with opacity, the opacity incorrectly applies to the pen
351 // when exporting to PDF/print devices
352 p->setBrush( useSelectedColor ? mSelBrush : mBrush );
353 p->setPen( Qt::NoPen );
354 _renderPolygon( p, points, rings, context );
355
356 p->setPen( useSelectedColor ? mSelPen : mPen );
357 p->setBrush( Qt::NoBrush );
358 _renderPolygon( p, points, rings, context );
359 }
360
361 if ( !offset.isNull() )
362 {
363 p->translate( -offset );
364 }
365}
366
368{
369 QVariantMap map;
370 map[u"color"_s] = QgsColorUtils::colorToString( mColor );
372 map[u"outline_color"_s] = QgsColorUtils::colorToString( mStrokeColor );
373 map[u"outline_style"_s] = QgsSymbolLayerUtils::encodePenStyle( mStrokeStyle );
374 map[u"outline_width"_s] = QString::number( mStrokeWidth );
375 map[u"outline_width_unit"_s] = QgsUnitTypes::encodeUnit( mStrokeWidthUnit );
376 map[u"border_width_map_unit_scale"_s] = QgsSymbolLayerUtils::encodeMapUnitScale( mStrokeWidthMapUnitScale );
378 map[u"offset"_s] = QgsSymbolLayerUtils::encodePoint( mOffset );
379 map[u"offset_unit"_s] = QgsUnitTypes::encodeUnit( mOffsetUnit );
380 map[u"offset_map_unit_scale"_s] = QgsSymbolLayerUtils::encodeMapUnitScale( mOffsetMapUnitScale );
381 return map;
382}
383
385{
386 auto sl = std::make_unique< QgsSimpleFillSymbolLayer >( mColor, mBrushStyle, mStrokeColor, mStrokeStyle, mStrokeWidth, mPenJoinStyle );
387 sl->setOffset( mOffset );
388 sl->setOffsetUnit( mOffsetUnit );
389 sl->setOffsetMapUnitScale( mOffsetMapUnitScale );
390 sl->setStrokeWidthUnit( mStrokeWidthUnit );
391 sl->setStrokeWidthMapUnitScale( mStrokeWidthMapUnitScale );
392 copyCommonProperties( sl.get() );
393 return sl.release();
394}
395
396void QgsSimpleFillSymbolLayer::toSld( QDomDocument &doc, QDomElement &element, const QVariantMap &props ) const
397{
398 QgsSldExportContext context;
399 context.setExtraProperties( props );
400 toSld( doc, element, context );
401}
402
403bool QgsSimpleFillSymbolLayer::toSld( QDomDocument &doc, QDomElement &element, QgsSldExportContext &context ) const
404{
405 if ( mBrushStyle == Qt::NoBrush && mStrokeStyle == Qt::NoPen )
406 return true;
407
408 const QVariantMap props = context.extraProperties();
409 QDomElement symbolizerElem = doc.createElement( u"se:PolygonSymbolizer"_s );
410 if ( !props.value( u"uom"_s, QString() ).toString().isEmpty() )
411 symbolizerElem.setAttribute( u"uom"_s, props.value( u"uom"_s, QString() ).toString() );
412 element.appendChild( symbolizerElem );
413
414 // <Geometry>
415 QgsSymbolLayerUtils::createGeometryElement( doc, symbolizerElem, props.value( u"geom"_s, QString() ).toString(), context );
416
417 // Export to PNG
418 bool exportOk { false };
419 if ( !context.exportFilePath().isEmpty() && context.exportOptions().testFlag( Qgis::SldExportOption::Png ) )
420 {
421 const QImage image { toTiledPatternImage() };
422 if ( !image.isNull() )
423 {
424 // <Fill>
425 QDomElement fillElem = doc.createElement( u"se:Fill"_s );
426 symbolizerElem.appendChild( fillElem );
427 QDomElement graphicFillElem = doc.createElement( u"se:GraphicFill"_s );
428 fillElem.appendChild( graphicFillElem );
429 QDomElement graphicElem = doc.createElement( u"se:Graphic"_s );
430 graphicFillElem.appendChild( graphicElem );
431 QgsRenderContext renderContext;
432 const QFileInfo info { context.exportFilePath() };
433 QString pngPath { info.completeSuffix().isEmpty() ? context.exportFilePath() : context.exportFilePath().chopped( info.completeSuffix().length() ).append( u"png"_s ) };
434 pngPath = QgsFileUtils::uniquePath( pngPath );
435 image.save( pngPath );
436 QgsSymbolLayerUtils::externalGraphicToSld( doc, graphicElem, QFileInfo( pngPath ).fileName(), u"image/png"_s, QColor(), image.height() );
437 exportOk = true;
438 }
439 }
440
441 if ( !exportOk )
442 {
443 if ( mBrushStyle != Qt::NoBrush )
444 {
445 QColor color { mColor };
446
447 // Apply alpha from symbol
448 bool ok;
449 const double alpha { props.value( u"alpha"_s, QVariant() ).toDouble( &ok ) };
450 if ( ok )
451 {
452 color.setAlphaF( color.alphaF() * alpha );
453 }
454 // <Fill>
455 QDomElement fillElem = doc.createElement( u"se:Fill"_s );
456 symbolizerElem.appendChild( fillElem );
457 QgsSymbolLayerUtils::fillToSld( doc, fillElem, context, mBrushStyle, color );
458 }
459
460 if ( mStrokeStyle != Qt::NoPen )
461 {
462 // <Stroke>
463 QDomElement strokeElem = doc.createElement( u"se:Stroke"_s );
464 symbolizerElem.appendChild( strokeElem );
466 // Apply alpha from symbol
467 bool ok;
468 const double alpha { props.value( u"alpha"_s, QVariant() ).toDouble( &ok ) };
469 QColor strokeColor { mStrokeColor };
470 if ( ok )
471 {
472 strokeColor.setAlphaF( strokeColor.alphaF() * alpha );
473 }
475 }
476 }
477
478 // <se:Displacement>
481 return true;
482}
483
484QString QgsSimpleFillSymbolLayer::ogrFeatureStyle( double mmScaleFactor, double mapUnitScaleFactor ) const
485{
486 //brush
487 QString symbolStyle;
488 symbolStyle.append( QgsSymbolLayerUtils::ogrFeatureStyleBrush( mColor ) );
489 symbolStyle.append( ';' );
490 //pen
491 symbolStyle.append( QgsSymbolLayerUtils::ogrFeatureStylePen( mStrokeWidth, mmScaleFactor, mapUnitScaleFactor, mStrokeColor, mPenJoinStyle ) );
492 return symbolStyle;
493}
494
495std::unique_ptr<QgsSymbolLayer> QgsSimpleFillSymbolLayer::createFromSld( QDomElement &element )
496{
497 QColor color, strokeColor;
498 Qt::BrushStyle fillStyle;
499 Qt::PenStyle strokeStyle;
500 double strokeWidth;
501
502 QDomElement fillElem = element.firstChildElement( u"Fill"_s );
503 QgsSymbolLayerUtils::fillFromSld( fillElem, fillStyle, color );
504
505 QDomElement strokeElem = element.firstChildElement( u"Stroke"_s );
507
508 QPointF offset;
510
511 double scaleFactor = 1.0;
512 const QString uom = element.attribute( u"uom"_s );
513 Qgis::RenderUnit sldUnitSize = QgsSymbolLayerUtils::decodeSldUom( uom, &scaleFactor );
514 offset.setX( offset.x() * scaleFactor );
515 offset.setY( offset.y() * scaleFactor );
516 strokeWidth = strokeWidth * scaleFactor;
517
518 auto sl = std::make_unique< QgsSimpleFillSymbolLayer >( color, fillStyle, strokeColor, strokeStyle, strokeWidth );
519 sl->setOutputUnit( sldUnitSize );
520 sl->setOffset( offset );
521 return sl;
522}
523
525{
526 double penBleed = context.convertToPainterUnits( mStrokeStyle == Qt::NoPen ? 0 : ( mStrokeWidth / 2.0 ), mStrokeWidthUnit, mStrokeWidthMapUnitScale );
527 double offsetBleed = context.convertToPainterUnits( std::max( std::fabs( mOffset.x() ), std::fabs( mOffset.y() ) ), mOffsetUnit, mOffsetMapUnitScale );
528 return penBleed + offsetBleed;
529}
530
541
552
563
565{
566 return mStrokeStyle;
567}
568
570{
571 QColor c = mColor;
573 {
575 }
576 return c;
577}
578
580{
581 return mBrushStyle;
582}
583
585{
586 QPixmap pixmap( QSize( 32, 32 ) );
587 pixmap.fill( Qt::transparent );
588 QPainter painter;
589 painter.begin( &pixmap );
590 painter.setRenderHint( QPainter::Antialiasing );
591 QgsRenderContext renderContext = QgsRenderContext::fromQPainter( &painter );
596 QgsSymbolRenderContext symbolContext( renderContext, Qgis::RenderUnit::Pixels, 1.0, false, Qgis::SymbolRenderHints() );
597
598 std::unique_ptr< QgsSimpleFillSymbolLayer > layerClone( clone() );
599 layerClone->setStrokeStyle( Qt::PenStyle::NoPen );
600 layerClone->drawPreviewIcon( symbolContext, pixmap.size() );
601 painter.end();
602 return pixmap.toImage();
603}
604
605//QgsGradientFillSymbolLayer
606
620
623
624std::unique_ptr<QgsSymbolLayer> QgsGradientFillSymbolLayer::create( const QVariantMap &props )
625{
626 //default to a two-color, linear gradient with feature mode and pad spreading
631 //default to gradient from the default fill color to white
632 QColor color = DEFAULT_SIMPLEFILL_COLOR, color2 = Qt::white;
633 QPointF referencePoint1 = QPointF( 0.5, 0 );
634 bool refPoint1IsCentroid = false;
635 QPointF referencePoint2 = QPointF( 0.5, 1 );
636 bool refPoint2IsCentroid = false;
637 double angle = 0;
638 QPointF offset;
639
640 //update gradient properties from props
641 if ( props.contains( u"type"_s ) )
642 type = static_cast< Qgis::GradientType >( props[u"type"_s].toInt() );
643 if ( props.contains( u"coordinate_mode"_s ) )
644 coordinateMode = static_cast< Qgis::SymbolCoordinateReference >( props[u"coordinate_mode"_s].toInt() );
645 if ( props.contains( u"spread"_s ) )
646 gradientSpread = static_cast< Qgis::GradientSpread >( props[u"spread"_s].toInt() );
647 if ( props.contains( u"color_type"_s ) )
648 colorType = static_cast< Qgis::GradientColorSource >( props[u"color_type"_s].toInt() );
649 if ( props.contains( u"gradient_color"_s ) )
650 {
651 //pre 2.5 projects used "gradient_color"
652 color = QgsColorUtils::colorFromString( props[u"gradient_color"_s].toString() );
653 }
654 else if ( props.contains( u"color"_s ) )
655 {
656 color = QgsColorUtils::colorFromString( props[u"color"_s].toString() );
657 }
658 if ( props.contains( u"gradient_color2"_s ) )
659 {
660 color2 = QgsColorUtils::colorFromString( props[u"gradient_color2"_s].toString() );
661 }
662
663 if ( props.contains( u"reference_point1"_s ) )
664 referencePoint1 = QgsSymbolLayerUtils::decodePoint( props[u"reference_point1"_s].toString() );
665 if ( props.contains( u"reference_point1_iscentroid"_s ) )
666 refPoint1IsCentroid = props[u"reference_point1_iscentroid"_s].toInt();
667 if ( props.contains( u"reference_point2"_s ) )
668 referencePoint2 = QgsSymbolLayerUtils::decodePoint( props[u"reference_point2"_s].toString() );
669 if ( props.contains( u"reference_point2_iscentroid"_s ) )
670 refPoint2IsCentroid = props[u"reference_point2_iscentroid"_s].toInt();
671 if ( props.contains( u"angle"_s ) )
672 angle = props[u"angle"_s].toDouble();
673
674 if ( props.contains( u"offset"_s ) )
675 offset = QgsSymbolLayerUtils::decodePoint( props[u"offset"_s].toString() );
676
677 //attempt to create color ramp from props
678 std::unique_ptr<QgsColorRamp> gradientRamp;
679 if ( props.contains( u"rampType"_s ) && props[u"rampType"_s] == QgsCptCityColorRamp::typeString() )
680 {
681 gradientRamp = QgsCptCityColorRamp::create( props );
682 }
683 else
684 {
685 gradientRamp = QgsGradientColorRamp::create( props );
686 }
687
688 //create a new gradient fill layer with desired properties
689 auto sl = std::make_unique< QgsGradientFillSymbolLayer >( color, color2, colorType, type, coordinateMode, gradientSpread );
690 sl->setOffset( offset );
691 if ( props.contains( u"offset_unit"_s ) )
692 sl->setOffsetUnit( QgsUnitTypes::decodeRenderUnit( props[u"offset_unit"_s].toString() ) );
693 if ( props.contains( u"offset_map_unit_scale"_s ) )
694 sl->setOffsetMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( props[u"offset_map_unit_scale"_s].toString() ) );
695 sl->setReferencePoint1( referencePoint1 );
696 sl->setReferencePoint1IsCentroid( refPoint1IsCentroid );
697 sl->setReferencePoint2( referencePoint2 );
698 sl->setReferencePoint2IsCentroid( refPoint2IsCentroid );
699 sl->setAngle( angle );
700 if ( gradientRamp )
701 sl->setColorRamp( gradientRamp.release() );
702
703 sl->restoreOldDataDefinedProperties( props );
704
705 return sl;
706}
707
712
714{
715 mGradientRamp.reset( ramp );
716}
717
719{
720 return u"GradientFill"_s;
721}
722
723void QgsGradientFillSymbolLayer::applyDataDefinedSymbology( QgsSymbolRenderContext &context, const QPolygonF &points )
724{
726 {
727 //shortcut
729 return;
730 }
731
732 bool ok;
733
734 //first gradient color
735 QColor color = mColor;
737 {
740 color.setAlphaF( context.opacity() * color.alphaF() );
741 }
742
743 //second gradient color
744 QColor color2 = mColor2;
746 {
749 color2.setAlphaF( context.opacity() * color2.alphaF() );
750 }
751
752 //gradient rotation angle
753 double angle = mAngle;
755 {
758 }
759
760 //gradient type
763 {
764 QString currentType = mDataDefinedProperties.valueAsString( QgsSymbolLayer::Property::GradientType, context.renderContext().expressionContext(), QString(), &ok );
765 if ( ok )
766 {
767 static constexpr auto GRADIENT_MAP = makeDataDefinedStringDecoder<Qgis::GradientType>( {
768 { u"linear", Qgis::GradientType::Linear },
769 { u"radial", Qgis::GradientType::Radial },
770 { u"conical", Qgis::GradientType::Conical },
771 } );
772
773 auto evaluatedGradient = GRADIENT_MAP.lookup( currentType );
774 if ( evaluatedGradient )
775 {
776 gradientType = *evaluatedGradient;
777 }
778 }
779 }
780
781 //coordinate mode
784 {
785 QString currentCoordMode = mDataDefinedProperties.valueAsString( QgsSymbolLayer::Property::CoordinateMode, context.renderContext().expressionContext(), QString(), &ok );
786 if ( ok )
787 {
788 static constexpr auto COORDINATE_MAP = makeDataDefinedStringDecoder<Qgis::SymbolCoordinateReference>( {
791 } );
792
793 auto evaluatedMode = COORDINATE_MAP.lookup( currentCoordMode );
794 if ( evaluatedMode )
795 {
796 coordinateMode = *evaluatedMode;
797 }
798 }
799 }
800
801 //gradient spread
804 {
805 QString currentSpread = mDataDefinedProperties.valueAsString( QgsSymbolLayer::Property::GradientSpread, context.renderContext().expressionContext(), QString(), &ok );
806 if ( ok )
807 {
808 static constexpr auto SPREAD_MAP = makeDataDefinedStringDecoder<Qgis::GradientSpread>( {
809 { u"pad", Qgis::GradientSpread::Pad },
810 { u"repeat", Qgis::GradientSpread::Repeat },
811 { u"reflect", Qgis::GradientSpread::Reflect },
812 } );
813
814 auto evaluatedSpread = SPREAD_MAP.lookup( currentSpread );
815 if ( evaluatedSpread )
816 {
817 spread = *evaluatedSpread;
818 }
819 }
820 }
821
822 //reference point 1 x & y
823 double refPoint1X = mReferencePoint1.x();
825 {
826 context.setOriginalValueVariable( refPoint1X );
828 }
829 double refPoint1Y = mReferencePoint1.y();
831 {
832 context.setOriginalValueVariable( refPoint1Y );
834 }
835 bool refPoint1IsCentroid = mReferencePoint1IsCentroid;
837 {
838 context.setOriginalValueVariable( refPoint1IsCentroid );
839 refPoint1IsCentroid = mDataDefinedProperties.valueAsBool( QgsSymbolLayer::Property::GradientReference1IsCentroid, context.renderContext().expressionContext(), refPoint1IsCentroid );
840 }
841
842 //reference point 2 x & y
843 double refPoint2X = mReferencePoint2.x();
845 {
846 context.setOriginalValueVariable( refPoint2X );
848 }
849 double refPoint2Y = mReferencePoint2.y();
851 {
852 context.setOriginalValueVariable( refPoint2Y );
854 }
855 bool refPoint2IsCentroid = mReferencePoint2IsCentroid;
857 {
858 context.setOriginalValueVariable( refPoint2IsCentroid );
859 refPoint2IsCentroid = mDataDefinedProperties.valueAsBool( QgsSymbolLayer::Property::GradientReference2IsCentroid, context.renderContext().expressionContext(), refPoint2IsCentroid );
860 }
861
862 if ( refPoint1IsCentroid || refPoint2IsCentroid )
863 {
864 //either the gradient is starting or ending at a centroid, so calculate it
865 QPointF centroid = QgsSymbolLayerUtils::polygonCentroid( points );
866 //centroid coordinates need to be scaled to a range [0, 1] relative to polygon bounds
867 QRectF bbox = points.boundingRect();
868 double centroidX = ( centroid.x() - bbox.left() ) / bbox.width();
869 double centroidY = ( centroid.y() - bbox.top() ) / bbox.height();
870
871 if ( refPoint1IsCentroid )
872 {
873 refPoint1X = centroidX;
874 refPoint1Y = centroidY;
875 }
876 if ( refPoint2IsCentroid )
877 {
878 refPoint2X = centroidX;
879 refPoint2Y = centroidY;
880 }
881 }
882
883 //update gradient with data defined values
884 applyGradient( context, mBrush, color, color2, mGradientColorType, mGradientRamp.get(), gradientType, coordinateMode, spread, QPointF( refPoint1X, refPoint1Y ), QPointF( refPoint2X, refPoint2Y ), angle );
885}
886
887QPointF QgsGradientFillSymbolLayer::rotateReferencePoint( QPointF refPoint, double angle )
888{
889 //rotate a reference point by a specified angle around the point (0.5, 0.5)
890
891 //create a line from the centrepoint of a rectangle bounded by (0, 0) and (1, 1) to the reference point
892 QLineF refLine = QLineF( QPointF( 0.5, 0.5 ), refPoint );
893 //rotate this line by the current rotation angle
894 refLine.setAngle( refLine.angle() + angle );
895 //get new end point of line
896 QPointF rotatedReferencePoint = refLine.p2();
897 //make sure coords of new end point is within [0, 1]
898 if ( rotatedReferencePoint.x() > 1 )
899 rotatedReferencePoint.setX( 1 );
900 if ( rotatedReferencePoint.x() < 0 )
901 rotatedReferencePoint.setX( 0 );
902 if ( rotatedReferencePoint.y() > 1 )
903 rotatedReferencePoint.setY( 1 );
904 if ( rotatedReferencePoint.y() < 0 )
905 rotatedReferencePoint.setY( 0 );
906
907 return rotatedReferencePoint;
908}
909
910void QgsGradientFillSymbolLayer::applyGradient(
911 const QgsSymbolRenderContext &context,
912 QBrush &brush,
913 const QColor &color,
914 const QColor &color2,
915 Qgis::GradientColorSource gradientColorType,
916 QgsColorRamp *gradientRamp,
917 Qgis::GradientType gradientType,
918 Qgis::SymbolCoordinateReference coordinateMode,
919 Qgis::GradientSpread gradientSpread,
920 QPointF referencePoint1,
921 QPointF referencePoint2,
922 const double angle
923)
924{
925 //update alpha of gradient colors
926 QColor fillColor = color;
927 fillColor.setAlphaF( context.opacity() * fillColor.alphaF() );
928 QColor fillColor2 = color2;
929 fillColor2.setAlphaF( context.opacity() * fillColor2.alphaF() );
930
931 //rotate reference points
932 QPointF rotatedReferencePoint1 = !qgsDoubleNear( angle, 0.0 ) ? rotateReferencePoint( referencePoint1, angle ) : referencePoint1;
933 QPointF rotatedReferencePoint2 = !qgsDoubleNear( angle, 0.0 ) ? rotateReferencePoint( referencePoint2, angle ) : referencePoint2;
934
935 //create a QGradient with the desired properties
936 QGradient gradient;
937 switch ( gradientType )
938 {
940 gradient = QLinearGradient( rotatedReferencePoint1, rotatedReferencePoint2 );
941 break;
943 gradient = QRadialGradient( rotatedReferencePoint1, QLineF( rotatedReferencePoint1, rotatedReferencePoint2 ).length() );
944 break;
946 gradient = QConicalGradient( rotatedReferencePoint1, QLineF( rotatedReferencePoint1, rotatedReferencePoint2 ).angle() );
947 break;
948 }
949 switch ( coordinateMode )
950 {
952 gradient.setCoordinateMode( QGradient::ObjectBoundingMode );
953 break;
955 gradient.setCoordinateMode( QGradient::StretchToDeviceMode );
956 break;
957 }
958 switch ( gradientSpread )
959 {
961 gradient.setSpread( QGradient::PadSpread );
962 break;
964 gradient.setSpread( QGradient::ReflectSpread );
965 break;
967 gradient.setSpread( QGradient::RepeatSpread );
968 break;
969 }
970
971 //add stops to gradient
973 && gradientRamp
974 && ( gradientRamp->type() == QgsGradientColorRamp::typeString() || gradientRamp->type() == QgsCptCityColorRamp::typeString() ) )
975 {
976 //color ramp gradient
977 QgsGradientColorRamp *gradRamp = static_cast<QgsGradientColorRamp *>( gradientRamp );
978 gradRamp->addStopsToGradient( &gradient, context.opacity() );
979 }
980 else
981 {
982 //two color gradient
983 gradient.setColorAt( 0.0, fillColor );
984 gradient.setColorAt( 1.0, fillColor2 );
985 }
986
987 //update QBrush use gradient
988 brush = QBrush( gradient );
989}
990
992{
993 QColor selColor = context.renderContext().selectionColor();
994 if ( !SELECTION_IS_OPAQUE )
995 selColor.setAlphaF( context.opacity() );
996 mSelBrush = QBrush( selColor );
997}
998
1000{
1001 Q_UNUSED( context )
1002}
1003
1004void QgsGradientFillSymbolLayer::renderPolygon( const QPolygonF &points, const QVector<QPolygonF> *rings, QgsSymbolRenderContext &context )
1005{
1006 QPainter *p = context.renderContext().painter();
1007 if ( !p )
1008 {
1009 return;
1010 }
1011
1012 applyDataDefinedSymbology( context, points );
1013
1014 const bool useSelectedColor = shouldRenderUsingSelectionColor( context );
1015 p->setBrush( useSelectedColor ? mSelBrush : mBrush );
1016 p->setPen( Qt::NoPen );
1017
1018 QPointF offset = mOffset;
1020 {
1022 const QVariant val = mDataDefinedProperties.value( QgsSymbolLayer::Property::Offset, context.renderContext().expressionContext(), QString() );
1023 bool ok = false;
1024 const QPointF res = QgsSymbolLayerUtils::toPoint( val, &ok );
1025 if ( ok )
1026 offset = res;
1027 }
1028
1029 if ( !offset.isNull() )
1030 {
1033 p->translate( offset );
1034 }
1035
1036 _renderPolygon( p, points, rings, context );
1037
1038 if ( !offset.isNull() )
1039 {
1040 p->translate( -offset );
1041 }
1042}
1043
1045{
1046 QVariantMap map;
1047 map[u"color"_s] = QgsColorUtils::colorToString( mColor );
1048 map[u"gradient_color2"_s] = QgsColorUtils::colorToString( mColor2 );
1049 map[u"color_type"_s] = QString::number( static_cast< int >( mGradientColorType ) );
1050 map[u"type"_s] = QString::number( static_cast<int>( mGradientType ) );
1051 map[u"coordinate_mode"_s] = QString::number( static_cast< int >( mCoordinateMode ) );
1052 map[u"spread"_s] = QString::number( static_cast< int >( mGradientSpread ) );
1053 map[u"reference_point1"_s] = QgsSymbolLayerUtils::encodePoint( mReferencePoint1 );
1054 map[u"reference_point1_iscentroid"_s] = QString::number( mReferencePoint1IsCentroid );
1055 map[u"reference_point2"_s] = QgsSymbolLayerUtils::encodePoint( mReferencePoint2 );
1056 map[u"reference_point2_iscentroid"_s] = QString::number( mReferencePoint2IsCentroid );
1057 map[u"angle"_s] = QString::number( mAngle );
1058 map[u"offset"_s] = QgsSymbolLayerUtils::encodePoint( mOffset );
1059 map[u"offset_unit"_s] = QgsUnitTypes::encodeUnit( mOffsetUnit );
1060 map[u"offset_map_unit_scale"_s] = QgsSymbolLayerUtils::encodeMapUnitScale( mOffsetMapUnitScale );
1061 if ( mGradientRamp )
1062 {
1063 map.insert( mGradientRamp->properties() );
1064 }
1065 return map;
1066}
1067
1069{
1070 auto sl = std::make_unique< QgsGradientFillSymbolLayer >( mColor, mColor2, mGradientColorType, mGradientType, mCoordinateMode, mGradientSpread );
1071 if ( mGradientRamp )
1072 sl->setColorRamp( mGradientRamp->clone() );
1073 sl->setReferencePoint1( mReferencePoint1 );
1074 sl->setReferencePoint1IsCentroid( mReferencePoint1IsCentroid );
1075 sl->setReferencePoint2( mReferencePoint2 );
1076 sl->setReferencePoint2IsCentroid( mReferencePoint2IsCentroid );
1077 sl->setAngle( mAngle );
1078 sl->setOffset( mOffset );
1079 sl->setOffsetUnit( mOffsetUnit );
1080 sl->setOffsetMapUnitScale( mOffsetMapUnitScale );
1081 copyCommonProperties( sl.get() );
1082 return sl.release();
1083}
1084
1086{
1087 double offsetBleed = context.convertToPainterUnits( std::max( std::fabs( mOffset.x() ), std::fabs( mOffset.y() ) ), mOffsetUnit, mOffsetMapUnitScale );
1088 return offsetBleed;
1089}
1090
1095
1100
1105
1110
1115
1120
1121//QgsShapeburstFillSymbolLayer
1122
1124 : mBlurRadius( blurRadius )
1125 , mUseWholeShape( useWholeShape )
1126 , mMaxDistance( maxDistance )
1127 , mColorType( colorType )
1128 , mColor2( color2 )
1129{
1130 mColor = color;
1131}
1132
1134
1135std::unique_ptr<QgsSymbolLayer> QgsShapeburstFillSymbolLayer::create( const QVariantMap &props )
1136{
1137 //default to a two-color gradient
1139 QColor color = DEFAULT_SIMPLEFILL_COLOR, color2 = Qt::white;
1140 int blurRadius = 0;
1141 bool useWholeShape = true;
1142 double maxDistance = 5;
1143 QPointF offset;
1144
1145 //update fill properties from props
1146 if ( props.contains( u"color_type"_s ) )
1147 {
1148 colorType = static_cast< Qgis::GradientColorSource >( props[u"color_type"_s].toInt() );
1149 }
1150 if ( props.contains( u"shapeburst_color"_s ) )
1151 {
1152 //pre 2.5 projects used "shapeburst_color"
1153 color = QgsColorUtils::colorFromString( props[u"shapeburst_color"_s].toString() );
1154 }
1155 else if ( props.contains( u"color"_s ) )
1156 {
1157 color = QgsColorUtils::colorFromString( props[u"color"_s].toString() );
1158 }
1159
1160 if ( props.contains( u"shapeburst_color2"_s ) )
1161 {
1162 //pre 2.5 projects used "shapeburst_color2"
1163 color2 = QgsColorUtils::colorFromString( props[u"shapeburst_color2"_s].toString() );
1164 }
1165 else if ( props.contains( u"gradient_color2"_s ) )
1166 {
1167 color2 = QgsColorUtils::colorFromString( props[u"gradient_color2"_s].toString() );
1168 }
1169 if ( props.contains( u"blur_radius"_s ) )
1170 {
1171 blurRadius = props[u"blur_radius"_s].toInt();
1172 }
1173 if ( props.contains( u"use_whole_shape"_s ) )
1174 {
1175 useWholeShape = props[u"use_whole_shape"_s].toInt();
1176 }
1177 if ( props.contains( u"max_distance"_s ) )
1178 {
1179 maxDistance = props[u"max_distance"_s].toDouble();
1180 }
1181 if ( props.contains( u"offset"_s ) )
1182 {
1183 offset = QgsSymbolLayerUtils::decodePoint( props[u"offset"_s].toString() );
1184 }
1185
1186 //attempt to create color ramp from props
1187 std::unique_ptr<QgsColorRamp> gradientRamp;
1188 if ( props.contains( u"rampType"_s ) && props[u"rampType"_s] == QgsCptCityColorRamp::typeString() )
1189 {
1190 gradientRamp = QgsCptCityColorRamp::create( props );
1191 }
1192 else
1193 {
1194 gradientRamp = QgsGradientColorRamp::create( props );
1195 }
1196
1197 //create a new shapeburst fill layer with desired properties
1198 auto sl = std::make_unique< QgsShapeburstFillSymbolLayer >( color, color2, colorType, blurRadius, useWholeShape, maxDistance );
1199 sl->setOffset( offset );
1200 if ( props.contains( u"offset_unit"_s ) )
1201 {
1202 sl->setOffsetUnit( QgsUnitTypes::decodeRenderUnit( props[u"offset_unit"_s].toString() ) );
1203 }
1204 if ( props.contains( u"distance_unit"_s ) )
1205 {
1206 sl->setDistanceUnit( QgsUnitTypes::decodeRenderUnit( props[u"distance_unit"_s].toString() ) );
1207 }
1208 if ( props.contains( u"offset_map_unit_scale"_s ) )
1209 {
1210 sl->setOffsetMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( props[u"offset_map_unit_scale"_s].toString() ) );
1211 }
1212 if ( props.contains( u"distance_map_unit_scale"_s ) )
1213 {
1214 sl->setDistanceMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( props[u"distance_map_unit_scale"_s].toString() ) );
1215 }
1216 if ( props.contains( u"ignore_rings"_s ) )
1217 {
1218 sl->setIgnoreRings( props[u"ignore_rings"_s].toInt() );
1219 }
1220 if ( gradientRamp )
1221 {
1222 sl->setColorRamp( gradientRamp.release() );
1223 }
1224
1225 sl->restoreOldDataDefinedProperties( props );
1226
1227 return sl;
1228}
1229
1231{
1232 return u"ShapeburstFill"_s;
1233}
1234
1239
1241{
1242 if ( mGradientRamp.get() == ramp )
1243 return;
1244
1245 mGradientRamp.reset( ramp );
1246}
1247
1248void QgsShapeburstFillSymbolLayer::applyDataDefinedSymbology( QgsSymbolRenderContext &context, QColor &color, QColor &color2, int &blurRadius, bool &useWholeShape, double &maxDistance, bool &ignoreRings )
1249{
1250 //first gradient color
1251 color = mColor;
1253 {
1256 }
1257
1258 //second gradient color
1259 color2 = mColor2;
1261 {
1264 }
1265
1266 //blur radius
1267 blurRadius = mBlurRadius;
1269 {
1270 context.setOriginalValueVariable( mBlurRadius );
1272 }
1273
1274 //use whole shape
1275 useWholeShape = mUseWholeShape;
1277 {
1278 context.setOriginalValueVariable( mUseWholeShape );
1280 }
1281
1282 //max distance
1283 maxDistance = mMaxDistance;
1285 {
1286 context.setOriginalValueVariable( mMaxDistance );
1288 }
1289
1290 //ignore rings
1291 ignoreRings = mIgnoreRings;
1293 {
1294 context.setOriginalValueVariable( mIgnoreRings );
1296 }
1297}
1298
1300{
1301 //TODO - check this
1302 QColor selColor = context.renderContext().selectionColor();
1303 if ( !SELECTION_IS_OPAQUE )
1304 selColor.setAlphaF( context.opacity() );
1305 mSelBrush = QBrush( selColor );
1306}
1307
1309{
1310 Q_UNUSED( context )
1311}
1312
1313void QgsShapeburstFillSymbolLayer::renderPolygon( const QPolygonF &points, const QVector<QPolygonF> *rings, QgsSymbolRenderContext &context )
1314{
1315 QPainter *p = context.renderContext().painter();
1316 if ( !p )
1317 {
1318 return;
1319 }
1320
1321 const bool useSelectedColor = shouldRenderUsingSelectionColor( context );
1322 if ( useSelectedColor )
1323 {
1324 //feature is selected, draw using selection style
1325 p->setBrush( mSelBrush );
1326 QPointF offset = mOffset;
1327
1329 {
1331 const QVariant val = mDataDefinedProperties.value( QgsSymbolLayer::Property::Offset, context.renderContext().expressionContext(), QString() );
1332 bool ok = false;
1333 const QPointF res = QgsSymbolLayerUtils::toPoint( val, &ok );
1334 if ( ok )
1335 offset = res;
1336 }
1337
1338 if ( !offset.isNull() )
1339 {
1340 offset.setX( context.renderContext().convertToPainterUnits( offset.x(), mOffsetUnit, mOffsetMapUnitScale ) );
1341 offset.setY( context.renderContext().convertToPainterUnits( offset.y(), mOffsetUnit, mOffsetMapUnitScale ) );
1342 p->translate( offset );
1343 }
1344 _renderPolygon( p, points, rings, context );
1345 if ( !offset.isNull() )
1346 {
1347 p->translate( -offset );
1348 }
1349 return;
1350 }
1351
1352 QColor color1, color2;
1353 int blurRadius;
1354 bool useWholeShape;
1355 double maxDistance;
1356 bool ignoreRings;
1357 //calculate data defined symbology
1358 applyDataDefinedSymbology( context, color1, color2, blurRadius, useWholeShape, maxDistance, ignoreRings );
1359
1360 //calculate max distance for shapeburst fill to extend from polygon boundary, in pixels
1361 int outputPixelMaxDist = 0;
1362 if ( !useWholeShape && !qgsDoubleNear( maxDistance, 0.0 ) )
1363 {
1364 //convert max distance to pixels
1365 outputPixelMaxDist = static_cast< int >( std::round( context.renderContext().convertToPainterUnits( maxDistance, mDistanceUnit, mDistanceMapUnitScale ) ) );
1366 }
1367
1368 //if we are using the two color mode, create a gradient ramp
1369 std::unique_ptr< QgsGradientColorRamp > twoColorGradientRamp;
1371 {
1372 twoColorGradientRamp = std::make_unique< QgsGradientColorRamp >( color1, color2 );
1373 }
1374
1375 //no stroke for shapeburst fills
1376 p->setPen( QPen( Qt::NoPen ) );
1377
1378 //calculate margin size in pixels so that QImage of polygon has sufficient space to draw the full blur effect
1379 int sideBuffer = 4 + ( blurRadius + 2 ) * 4;
1380 //create a QImage to draw shapeburst in
1381 int pointsWidth = static_cast< int >( std::round( points.boundingRect().width() ) );
1382 int pointsHeight = static_cast< int >( std::round( points.boundingRect().height() ) );
1383 int imWidth = pointsWidth + ( sideBuffer * 2 );
1384 int imHeight = pointsHeight + ( sideBuffer * 2 );
1385
1386 // these are all potentially very expensive operations, so check regularly if the job is canceled and abort responsively
1387 if ( context.renderContext().feedback() && context.renderContext().feedback()->isCanceled() )
1388 return;
1389
1390 auto fillImage = std::make_unique< QImage >( imWidth, imHeight, QImage::Format_ARGB32_Premultiplied );
1391 if ( fillImage->isNull() )
1392 {
1393 QgsMessageLog::logMessage( QObject::tr( "Could not allocate sufficient memory for shapeburst fill" ) );
1394 return;
1395 }
1396
1397 if ( context.renderContext().feedback() && context.renderContext().feedback()->isCanceled() )
1398 return;
1399
1400 //also create an image to store the alpha channel
1401 auto alphaImage = std::make_unique< QImage >( fillImage->width(), fillImage->height(), QImage::Format_ARGB32_Premultiplied );
1402 if ( alphaImage->isNull() )
1403 {
1404 QgsMessageLog::logMessage( QObject::tr( "Could not allocate sufficient memory for shapeburst fill" ) );
1405 return;
1406 }
1407
1408 if ( context.renderContext().feedback() && context.renderContext().feedback()->isCanceled() )
1409 return;
1410
1411 //Fill this image with black. Initially the distance transform is drawn in greyscale, where black pixels have zero distance from the
1412 //polygon boundary. Since we don't care about pixels which fall outside the polygon, we start with a black image and then draw over it the
1413 //polygon in white. The distance transform function then fills in the correct distance values for the white pixels.
1414 fillImage->fill( Qt::black );
1415
1416 if ( context.renderContext().feedback() && context.renderContext().feedback()->isCanceled() )
1417 return;
1418
1419 //initially fill the alpha channel image with a transparent color
1420 alphaImage->fill( Qt::transparent );
1421
1422 if ( context.renderContext().feedback() && context.renderContext().feedback()->isCanceled() )
1423 return;
1424
1425 //now, draw the polygon in the alpha channel image
1426 QPainter imgPainter;
1427 imgPainter.begin( alphaImage.get() );
1428 imgPainter.setRenderHint( QPainter::Antialiasing, true );
1429 imgPainter.setBrush( QBrush( Qt::white ) );
1430 imgPainter.setPen( QPen( Qt::black ) );
1431 imgPainter.translate( -points.boundingRect().left() + sideBuffer, -points.boundingRect().top() + sideBuffer );
1432 _renderPolygon( &imgPainter, points, rings, context );
1433 imgPainter.end();
1434
1435 if ( context.renderContext().feedback() && context.renderContext().feedback()->isCanceled() )
1436 return;
1437
1438 //now that we have a render of the polygon in white, draw this onto the shapeburst fill image too
1439 //(this avoids calling _renderPolygon twice, since that can be slow)
1440 imgPainter.begin( fillImage.get() );
1441 if ( !ignoreRings )
1442 {
1443 imgPainter.drawImage( 0, 0, *alphaImage );
1444 }
1445 else
1446 {
1447 //using ignore rings mode, so the alpha image can't be used
1448 //directly as the alpha channel contains polygon rings and we need
1449 //to draw now without any rings
1450 imgPainter.setBrush( QBrush( Qt::white ) );
1451 imgPainter.setPen( QPen( Qt::black ) );
1452 imgPainter.translate( -points.boundingRect().left() + sideBuffer, -points.boundingRect().top() + sideBuffer );
1453 _renderPolygon( &imgPainter, points, nullptr, context );
1454 }
1455 imgPainter.end();
1456
1457 if ( context.renderContext().feedback() && context.renderContext().feedback()->isCanceled() )
1458 return;
1459
1460 //apply distance transform to image, uses the current color ramp to calculate final pixel colors
1461 double *dtArray = distanceTransform( fillImage.get(), context.renderContext() );
1462
1463 //copy distance transform values back to QImage, shading by appropriate color ramp
1464 dtArrayToQImage( dtArray, fillImage.get(), mColorType == Qgis::GradientColorSource::SimpleTwoColor ? twoColorGradientRamp.get() : mGradientRamp.get(), context.renderContext(), useWholeShape, outputPixelMaxDist );
1465 if ( context.opacity() < 1 )
1466 {
1467 QgsImageOperation::multiplyOpacity( *fillImage, context.opacity(), context.renderContext().feedback() );
1468 }
1469
1470 //clean up some variables
1471 delete[] dtArray;
1472
1473 //apply blur if desired
1474 if ( blurRadius > 0 )
1475 {
1476 QgsImageOperation::stackBlur( *fillImage, blurRadius, false, context.renderContext().feedback() );
1477 }
1478
1479 //apply alpha channel to distance transform image, so that areas outside the polygon are transparent
1480 imgPainter.begin( fillImage.get() );
1481 imgPainter.setCompositionMode( QPainter::CompositionMode_DestinationIn );
1482 imgPainter.drawImage( 0, 0, *alphaImage );
1483 imgPainter.end();
1484 //we're finished with the alpha channel image now
1485 alphaImage.reset();
1486
1487 //draw shapeburst image in correct place in the destination painter
1488
1489 QgsScopedQPainterState painterState( p );
1490 QPointF offset = mOffset;
1492 {
1494 const QVariant val = mDataDefinedProperties.value( QgsSymbolLayer::Property::Offset, context.renderContext().expressionContext(), QString() );
1495 bool ok = false;
1496 const QPointF res = QgsSymbolLayerUtils::toPoint( val, &ok );
1497 if ( ok )
1498 offset = res;
1499 }
1500 if ( !offset.isNull() )
1501 {
1502 offset.setX( context.renderContext().convertToPainterUnits( offset.x(), mOffsetUnit, mOffsetMapUnitScale ) );
1503 offset.setY( context.renderContext().convertToPainterUnits( offset.y(), mOffsetUnit, mOffsetMapUnitScale ) );
1504 p->translate( offset );
1505 }
1506
1507 p->drawImage( points.boundingRect().left() - sideBuffer, points.boundingRect().top() - sideBuffer, *fillImage );
1508
1509 if ( !offset.isNull() )
1510 {
1511 p->translate( -offset );
1512 }
1513}
1514
1515//fast distance transform code, adapted from http://cs.brown.edu/~pff/dt/
1516
1517/* distance transform of a 1d function using squared distance */
1518void QgsShapeburstFillSymbolLayer::distanceTransform1d( double *f, int n, int *v, double *z, double *d )
1519{
1520 int k = 0;
1521 v[0] = 0;
1522 z[0] = -INF;
1523 z[1] = +INF;
1524 for ( int q = 1; q <= n - 1; q++ )
1525 {
1526 double s = ( ( f[q] + static_cast< double >( q ) * q ) - ( f[v[k]] + ( static_cast< double >( v[k] ) * v[k] ) ) ) / ( 2 * q - 2 * v[k] );
1527 while ( s <= z[k] )
1528 {
1529 k--;
1530 s = ( ( f[q] + static_cast< double >( q ) * q ) - ( f[v[k]] + ( static_cast< double >( v[k] ) * v[k] ) ) ) / ( 2 * q - 2 * v[k] );
1531 }
1532 k++;
1533 v[k] = q;
1534 z[k] = s;
1535 z[k + 1] = +INF;
1536 }
1537
1538 k = 0;
1539 for ( int q = 0; q <= n - 1; q++ )
1540 {
1541 while ( z[k + 1] < q )
1542 k++;
1543 d[q] = static_cast< double >( q - v[k] ) * ( q - v[k] ) + f[v[k]];
1544 }
1545}
1546
1547/* distance transform of 2d function using squared distance */
1548void QgsShapeburstFillSymbolLayer::distanceTransform2d( double *im, int width, int height, QgsRenderContext &context )
1549{
1550 int maxDimension = std::max( width, height );
1551 double *f = new double[maxDimension];
1552 int *v = new int[maxDimension];
1553 double *z = new double[maxDimension + 1];
1554 double *d = new double[maxDimension];
1555
1556 // transform along columns
1557 for ( int x = 0; x < width; x++ )
1558 {
1559 if ( context.renderingStopped() )
1560 break;
1561
1562 for ( int y = 0; y < height; y++ )
1563 {
1564 f[y] = im[x + static_cast< std::size_t>( y ) * width];
1565 }
1566 distanceTransform1d( f, height, v, z, d );
1567 for ( int y = 0; y < height; y++ )
1568 {
1569 im[x + static_cast< std::size_t>( y ) * width] = d[y];
1570 }
1571 }
1572
1573 // transform along rows
1574 for ( int y = 0; y < height; y++ )
1575 {
1576 if ( context.renderingStopped() )
1577 break;
1578
1579 for ( int x = 0; x < width; x++ )
1580 {
1581 f[x] = im[x + static_cast< std::size_t>( y ) * width];
1582 }
1583 distanceTransform1d( f, width, v, z, d );
1584 for ( int x = 0; x < width; x++ )
1585 {
1586 im[x + static_cast< std::size_t>( y ) * width] = d[x];
1587 }
1588 }
1589
1590 delete[] d;
1591 delete[] f;
1592 delete[] v;
1593 delete[] z;
1594}
1595
1596/* distance transform of a binary QImage */
1597double *QgsShapeburstFillSymbolLayer::distanceTransform( QImage *im, QgsRenderContext &context )
1598{
1599 int width = im->width();
1600 int height = im->height();
1601
1602 double *dtArray = new double[static_cast< std::size_t>( width ) * height];
1603
1604 //load qImage to array
1605 QRgb tmpRgb;
1606 std::size_t idx = 0;
1607 for ( int heightIndex = 0; heightIndex < height; ++heightIndex )
1608 {
1609 if ( context.renderingStopped() )
1610 break;
1611
1612 const QRgb *scanLine = reinterpret_cast< const QRgb * >( im->constScanLine( heightIndex ) );
1613 for ( int widthIndex = 0; widthIndex < width; ++widthIndex )
1614 {
1615 tmpRgb = scanLine[widthIndex];
1616 if ( qRed( tmpRgb ) == 0 )
1617 {
1618 //black pixel, so zero distance
1619 dtArray[idx] = 0;
1620 }
1621 else
1622 {
1623 //white pixel, so initially set distance as infinite
1624 dtArray[idx] = INF;
1625 }
1626 idx++;
1627 }
1628 }
1629
1630 //calculate squared distance transform
1631 distanceTransform2d( dtArray, width, height, context );
1632
1633 return dtArray;
1634}
1635
1636void QgsShapeburstFillSymbolLayer::dtArrayToQImage( double *array, QImage *im, QgsColorRamp *ramp, QgsRenderContext &context, bool useWholeShape, int maxPixelDistance )
1637{
1638 int width = im->width();
1639 int height = im->height();
1640
1641 //find maximum distance value
1642 double maxDistanceValue;
1643
1644 if ( useWholeShape )
1645 {
1646 //no max distance specified in symbol properties, so calculate from maximum value in distance transform results
1647 double dtMaxValue = array[0];
1648 for ( std::size_t i = 1; i < static_cast< std::size_t >( width ) * height; ++i )
1649 {
1650 if ( array[i] > dtMaxValue )
1651 {
1652 dtMaxValue = array[i];
1653 }
1654 }
1655
1656 //values in distance transform are squared
1657 maxDistanceValue = std::sqrt( dtMaxValue );
1658 }
1659 else
1660 {
1661 //use max distance set in symbol properties
1662 maxDistanceValue = maxPixelDistance;
1663 }
1664
1665 //update the pixels in the provided QImage
1666 std::size_t idx = 0;
1667 double squaredVal = 0;
1668 double pixVal = 0;
1669
1670 for ( int heightIndex = 0; heightIndex < height; ++heightIndex )
1671 {
1672 if ( context.renderingStopped() )
1673 break;
1674
1675 QRgb *scanLine = reinterpret_cast< QRgb * >( im->scanLine( heightIndex ) );
1676 for ( int widthIndex = 0; widthIndex < width; ++widthIndex )
1677 {
1678 //result of distance transform
1679 squaredVal = array[idx];
1680
1681 //scale result to fit in the range [0, 1]
1682 if ( maxDistanceValue > 0 )
1683 {
1684 pixVal = squaredVal > 0 ? std::min( ( std::sqrt( squaredVal ) / maxDistanceValue ), 1.0 ) : 0;
1685 }
1686 else
1687 {
1688 pixVal = 1.0;
1689 }
1690
1691 //convert value to color from ramp
1692 //premultiply ramp color since we are storing this in a ARGB32_Premultiplied QImage
1693 scanLine[widthIndex] = qPremultiply( ramp->color( pixVal ).rgba() );
1694 idx++;
1695 }
1696 }
1697}
1698
1700{
1701 QVariantMap map;
1702 map[u"color"_s] = QgsColorUtils::colorToString( mColor );
1703 map[u"gradient_color2"_s] = QgsColorUtils::colorToString( mColor2 );
1704 map[u"color_type"_s] = QString::number( static_cast< int >( mColorType ) );
1705 map[u"blur_radius"_s] = QString::number( mBlurRadius );
1706 map[u"use_whole_shape"_s] = QString::number( mUseWholeShape );
1707 map[u"max_distance"_s] = QString::number( mMaxDistance );
1708 map[u"distance_unit"_s] = QgsUnitTypes::encodeUnit( mDistanceUnit );
1709 map[u"distance_map_unit_scale"_s] = QgsSymbolLayerUtils::encodeMapUnitScale( mDistanceMapUnitScale );
1710 map[u"ignore_rings"_s] = QString::number( mIgnoreRings );
1711 map[u"offset"_s] = QgsSymbolLayerUtils::encodePoint( mOffset );
1712 map[u"offset_unit"_s] = QgsUnitTypes::encodeUnit( mOffsetUnit );
1713 map[u"offset_map_unit_scale"_s] = QgsSymbolLayerUtils::encodeMapUnitScale( mOffsetMapUnitScale );
1714 if ( mGradientRamp )
1715 {
1716 map.insert( mGradientRamp->properties() );
1717 }
1718
1719 return map;
1720}
1721
1723{
1724 auto sl = std::make_unique< QgsShapeburstFillSymbolLayer >( mColor, mColor2, mColorType, mBlurRadius, mUseWholeShape, mMaxDistance );
1725 if ( mGradientRamp )
1726 {
1727 sl->setColorRamp( mGradientRamp->clone() );
1728 }
1729 sl->setDistanceUnit( mDistanceUnit );
1730 sl->setDistanceMapUnitScale( mDistanceMapUnitScale );
1731 sl->setIgnoreRings( mIgnoreRings );
1732 sl->setOffset( mOffset );
1733 sl->setOffsetUnit( mOffsetUnit );
1734 sl->setOffsetMapUnitScale( mOffsetMapUnitScale );
1735 copyCommonProperties( sl.get() );
1736 return sl.release();
1737}
1738
1740{
1741 double offsetBleed = context.convertToPainterUnits( std::max( std::fabs( mOffset.x() ), std::fabs( mOffset.y() ) ), mOffsetUnit, mOffsetMapUnitScale );
1742 return offsetBleed;
1743}
1744
1749
1751{
1752 mDistanceUnit = unit;
1753 mOffsetUnit = unit;
1754}
1755
1757{
1758 if ( mDistanceUnit == mOffsetUnit )
1759 {
1760 return mDistanceUnit;
1761 }
1763}
1764
1766{
1767 return mDistanceUnit == Qgis::RenderUnit::MapUnits
1768 || mDistanceUnit == Qgis::RenderUnit::MetersInMapUnits
1769 || mOffsetUnit == Qgis::RenderUnit::MapUnits
1770 || mOffsetUnit == Qgis::RenderUnit::MetersInMapUnits;
1771}
1772
1774{
1775 mDistanceMapUnitScale = scale;
1776 mOffsetMapUnitScale = scale;
1777}
1778
1780{
1781 if ( mDistanceMapUnitScale == mOffsetMapUnitScale )
1782 {
1783 return mDistanceMapUnitScale;
1784 }
1785 return QgsMapUnitScale();
1786}
1787
1788
1789//QgsImageFillSymbolLayer
1790
1793
1795
1796void QgsImageFillSymbolLayer::renderPolygon( const QPolygonF &points, const QVector<QPolygonF> *rings, QgsSymbolRenderContext &context )
1797{
1798 QPainter *p = context.renderContext().painter();
1799 if ( !p )
1800 {
1801 return;
1802 }
1803
1805 applyDataDefinedSettings( context );
1806
1807 p->setPen( QPen( Qt::NoPen ) );
1808
1809 QTransform bkTransform = mBrush.transform();
1810 if ( applyBrushTransformFromContext( &context ) && !context.renderContext().textureOrigin().isNull() )
1811 {
1812 QPointF leftCorner = context.renderContext().textureOrigin();
1813 QTransform t = mBrush.transform();
1814 t.translate( leftCorner.x(), leftCorner.y() );
1815 mBrush.setTransform( t );
1816 }
1817 else
1818 {
1819 QTransform t = mBrush.transform();
1820 t.translate( 0, 0 );
1821 mBrush.setTransform( t );
1822 }
1823
1824 const bool useSelectedColor = shouldRenderUsingSelectionColor( context );
1825 if ( useSelectedColor )
1826 {
1827 QColor selColor = context.renderContext().selectionColor();
1828 p->setBrush( QBrush( selColor ) );
1829 _renderPolygon( p, points, rings, context );
1830 }
1831
1832 if ( !qgsDoubleNear( mNextAngle, 0.0 ) )
1833 {
1834 QTransform t = mBrush.transform();
1835 t.rotate( mNextAngle );
1836 mBrush.setTransform( t );
1837 }
1838 p->setBrush( mBrush );
1839 _renderPolygon( p, points, rings, context );
1840
1841 mBrush.setTransform( bkTransform );
1842}
1843
1848
1853
1858
1863
1865{
1866 double width = mStrokeWidth;
1868 {
1871 }
1872 return context.renderContext().convertToMapUnits( width, mStrokeWidthUnit );
1873}
1874
1876{
1877 return Qt::SolidLine;
1878#if 0
1879 if ( !mStroke )
1880 {
1881 return Qt::SolidLine;
1882 }
1883 else
1884 {
1885 return mStroke->dxfPenStyle();
1886 }
1887#endif //0
1888}
1889
1891{
1892 QVariantMap map;
1893 map.insert( u"coordinate_reference"_s, QgsSymbolLayerUtils::encodeCoordinateReference( mCoordinateReference ) );
1894 return map;
1895}
1896
1898{
1899 //coordinate reference
1902 {
1903 bool ok = false;
1904 QString string = mDataDefinedProperties.valueAsString( QgsSymbolLayer::Property::CoordinateMode, context->renderContext().expressionContext(), QString(), &ok );
1905 if ( ok )
1906 {
1908 if ( !ok )
1910 }
1911 }
1912
1914}
1915
1916
1917//QgsSVGFillSymbolLayer
1918
1921 , mPatternWidth( width )
1922{
1923 mStrokeWidth = 0.3;
1924 mAngle = angle;
1925 mColor = QColor( 255, 255, 255 );
1927}
1928
1929QgsSVGFillSymbolLayer::QgsSVGFillSymbolLayer( const QByteArray &svgData, double width, double angle )
1931 , mPatternWidth( width )
1932 , mSvgData( svgData )
1933{
1934 storeViewBox();
1935 mStrokeWidth = 0.3;
1936 mAngle = angle;
1937 mColor = QColor( 255, 255, 255 );
1938 setDefaultSvgParams();
1939}
1940
1942
1944{
1946 mPatternWidthUnit = unit;
1947 mSvgStrokeWidthUnit = unit;
1948 mStrokeWidthUnit = unit;
1949 if ( mStroke )
1950 mStroke->setOutputUnit( unit );
1951}
1952
1954{
1956 if ( mPatternWidthUnit != unit || mSvgStrokeWidthUnit != unit || mStrokeWidthUnit != unit )
1957 {
1959 }
1960 return unit;
1961}
1962
1964{
1966 mPatternWidthMapUnitScale = scale;
1967 mSvgStrokeWidthMapUnitScale = scale;
1968}
1969
1971{
1972 if ( QgsImageFillSymbolLayer::mapUnitScale() == mPatternWidthMapUnitScale && mPatternWidthMapUnitScale == mSvgStrokeWidthMapUnitScale && mSvgStrokeWidthMapUnitScale == mStrokeWidthMapUnitScale )
1973 {
1974 return mPatternWidthMapUnitScale;
1975 }
1976 return QgsMapUnitScale();
1977}
1978
1979void QgsSVGFillSymbolLayer::setSvgFilePath( const QString &svgPath )
1980{
1981 mSvgData = QgsApplication::svgCache()->getImageData( svgPath );
1982 storeViewBox();
1983
1984 mSvgFilePath = svgPath;
1985 setDefaultSvgParams();
1986}
1987
1988std::unique_ptr<QgsSymbolLayer> QgsSVGFillSymbolLayer::create( const QVariantMap &properties )
1989{
1990 QByteArray data;
1991 double width = 20;
1992 QString svgFilePath;
1993 double angle = 0.0;
1994
1995 if ( properties.contains( u"width"_s ) )
1996 {
1997 width = properties[u"width"_s].toDouble();
1998 }
1999 if ( properties.contains( u"svgFile"_s ) )
2000 {
2001 svgFilePath = properties[u"svgFile"_s].toString();
2002 }
2003 if ( properties.contains( u"angle"_s ) )
2004 {
2005 angle = properties[u"angle"_s].toDouble();
2006 }
2007
2008 std::unique_ptr< QgsSVGFillSymbolLayer > symbolLayer;
2009 if ( !svgFilePath.isEmpty() )
2010 {
2011 symbolLayer = std::make_unique< QgsSVGFillSymbolLayer >( svgFilePath, width, angle );
2012 }
2013 else
2014 {
2015 if ( properties.contains( u"data"_s ) )
2016 {
2017 data = QByteArray::fromHex( properties[u"data"_s].toString().toLocal8Bit() );
2018 }
2019 symbolLayer = std::make_unique< QgsSVGFillSymbolLayer >( data, width, angle );
2020 }
2021
2022 //svg parameters
2023 if ( properties.contains( u"svgFillColor"_s ) )
2024 {
2025 //pre 2.5 projects used "svgFillColor"
2026 symbolLayer->setSvgFillColor( QgsColorUtils::colorFromString( properties[u"svgFillColor"_s].toString() ) );
2027 }
2028 else if ( properties.contains( u"color"_s ) )
2029 {
2030 symbolLayer->setSvgFillColor( QgsColorUtils::colorFromString( properties[u"color"_s].toString() ) );
2031 }
2032 if ( properties.contains( u"svgOutlineColor"_s ) )
2033 {
2034 //pre 2.5 projects used "svgOutlineColor"
2035 symbolLayer->setSvgStrokeColor( QgsColorUtils::colorFromString( properties[u"svgOutlineColor"_s].toString() ) );
2036 }
2037 else if ( properties.contains( u"outline_color"_s ) )
2038 {
2039 symbolLayer->setSvgStrokeColor( QgsColorUtils::colorFromString( properties[u"outline_color"_s].toString() ) );
2040 }
2041 else if ( properties.contains( u"line_color"_s ) )
2042 {
2043 symbolLayer->setSvgStrokeColor( QgsColorUtils::colorFromString( properties[u"line_color"_s].toString() ) );
2044 }
2045 if ( properties.contains( u"svgOutlineWidth"_s ) )
2046 {
2047 //pre 2.5 projects used "svgOutlineWidth"
2048 symbolLayer->setSvgStrokeWidth( properties[u"svgOutlineWidth"_s].toDouble() );
2049 }
2050 else if ( properties.contains( u"outline_width"_s ) )
2051 {
2052 symbolLayer->setSvgStrokeWidth( properties[u"outline_width"_s].toDouble() );
2053 }
2054 else if ( properties.contains( u"line_width"_s ) )
2055 {
2056 symbolLayer->setSvgStrokeWidth( properties[u"line_width"_s].toDouble() );
2057 }
2058
2059 //units
2060 if ( properties.contains( u"pattern_width_unit"_s ) )
2061 {
2062 symbolLayer->setPatternWidthUnit( QgsUnitTypes::decodeRenderUnit( properties[u"pattern_width_unit"_s].toString() ) );
2063 }
2064 if ( properties.contains( u"pattern_width_map_unit_scale"_s ) )
2065 {
2066 symbolLayer->setPatternWidthMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( properties[u"pattern_width_map_unit_scale"_s].toString() ) );
2067 }
2068 if ( properties.contains( u"svg_outline_width_unit"_s ) )
2069 {
2070 symbolLayer->setSvgStrokeWidthUnit( QgsUnitTypes::decodeRenderUnit( properties[u"svg_outline_width_unit"_s].toString() ) );
2071 }
2072 if ( properties.contains( u"svg_outline_width_map_unit_scale"_s ) )
2073 {
2074 symbolLayer->setSvgStrokeWidthMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( properties[u"svg_outline_width_map_unit_scale"_s].toString() ) );
2075 }
2076 if ( properties.contains( u"outline_width_unit"_s ) )
2077 {
2078 symbolLayer->setStrokeWidthUnit( QgsUnitTypes::decodeRenderUnit( properties[u"outline_width_unit"_s].toString() ) );
2079 }
2080 if ( properties.contains( u"outline_width_map_unit_scale"_s ) )
2081 {
2082 symbolLayer->setStrokeWidthMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( properties[u"outline_width_map_unit_scale"_s].toString() ) );
2083 }
2084
2085 if ( properties.contains( u"parameters"_s ) )
2086 {
2087 const QVariantMap parameters = properties[u"parameters"_s].toMap();
2088 symbolLayer->setParameters( QgsProperty::variantMapToPropertyMap( parameters ) );
2089 }
2090
2091 symbolLayer->restoreOldDataDefinedProperties( properties );
2092
2093 return symbolLayer;
2094}
2095
2096void QgsSVGFillSymbolLayer::resolvePaths( QVariantMap &properties, const QgsPathResolver &pathResolver, bool saving )
2097{
2098 QVariantMap::iterator it = properties.find( u"svgFile"_s );
2099 if ( it != properties.end() )
2100 {
2101 if ( saving )
2102 it.value() = QgsSymbolLayerUtils::svgSymbolPathToName( it.value().toString(), pathResolver );
2103 else
2104 it.value() = QgsSymbolLayerUtils::svgSymbolNameToPath( it.value().toString(), pathResolver );
2105 }
2106}
2107
2109{
2110 return u"SVGFill"_s;
2111}
2112
2113void QgsSVGFillSymbolLayer::applyPattern(
2114 QBrush &brush,
2115 const QString &svgFilePath,
2116 double patternWidth,
2117 Qgis::RenderUnit patternWidthUnit,
2118 const QColor &svgFillColor,
2119 const QColor &svgStrokeColor,
2120 double svgStrokeWidth,
2121 Qgis::RenderUnit svgStrokeWidthUnit,
2122 const QgsSymbolRenderContext &context,
2123 const QgsMapUnitScale &patternWidthMapUnitScale,
2124 const QgsMapUnitScale &svgStrokeWidthMapUnitScale,
2125 const QgsStringMap svgParameters
2126)
2127{
2128 if ( mSvgViewBox.isNull() )
2129 {
2130 return;
2131 }
2132
2134
2135 if ( static_cast< int >( size ) < 1.0 || 10000.0 < size )
2136 {
2137 brush.setTextureImage( QImage() );
2138 }
2139 else
2140 {
2141 bool fitsInCache = true;
2143 QImage patternImage
2145 ->svgAsImage( svgFilePath, size, svgFillColor, svgStrokeColor, strokeWidth, context.renderContext().scaleFactor(), fitsInCache, 0, ( context.renderContext().flags() & Qgis::RenderContextFlag::RenderBlocking ), svgParameters );
2146 if ( !fitsInCache )
2147 {
2148 QPicture patternPict
2151 double hwRatio = 1.0;
2152 if ( patternPict.width() > 0 )
2153 {
2154 hwRatio = static_cast< double >( patternPict.height() ) / static_cast< double >( patternPict.width() );
2155 }
2156 patternImage = QImage( static_cast< int >( size ), static_cast< int >( size * hwRatio ), QImage::Format_ARGB32_Premultiplied );
2157 patternImage.fill( 0 ); // transparent background
2158
2159 QPainter p( &patternImage );
2160 p.drawPicture( QPointF( size / 2, size * hwRatio / 2 ), patternPict );
2161 }
2162
2163 QTransform brushTransform;
2164 if ( !qgsDoubleNear( context.opacity(), 1.0 ) )
2165 {
2166 QImage transparentImage = patternImage.copy();
2167 QgsSymbolLayerUtils::multiplyImageOpacity( &transparentImage, context.opacity() );
2168 brush.setTextureImage( transparentImage );
2169 }
2170 else
2171 {
2172 brush.setTextureImage( patternImage );
2173 }
2174 brush.setTransform( brushTransform );
2175 }
2176}
2177
2179{
2180 QgsStringMap evaluatedParameters = QgsSymbolLayerUtils::evaluatePropertiesMap( mParameters, context.renderContext().expressionContext() );
2181
2182 applyPattern( mBrush, mSvgFilePath, mPatternWidth, mPatternWidthUnit, mColor, mSvgStrokeColor, mSvgStrokeWidth, mSvgStrokeWidthUnit, context, mPatternWidthMapUnitScale, mSvgStrokeWidthMapUnitScale, evaluatedParameters );
2183
2184 if ( mStroke )
2185 {
2186 mStroke->setRenderHints( mStroke->renderHints() | Qgis::SymbolRenderHint::IsSymbolLayerSubSymbol );
2187 mStroke->startRender( context.renderContext(), context.fields() );
2188 }
2189}
2190
2192{
2193 if ( mStroke )
2194 {
2195 mStroke->stopRender( context.renderContext() );
2196 }
2197}
2198
2199void QgsSVGFillSymbolLayer::renderPolygon( const QPolygonF &points, const QVector<QPolygonF> *rings, QgsSymbolRenderContext &context )
2200{
2201 QgsImageFillSymbolLayer::renderPolygon( points, rings, context );
2202
2203 if ( mStroke )
2204 {
2205 const bool useSelectedColor = SELECT_FILL_BORDER && shouldRenderUsingSelectionColor( context );
2206 mStroke->renderPolyline( points, context.feature(), context.renderContext(), -1, useSelectedColor );
2207 if ( rings )
2208 {
2209 for ( auto ringIt = rings->constBegin(); ringIt != rings->constEnd(); ++ringIt )
2210 {
2211 mStroke->renderPolyline( *ringIt, context.feature(), context.renderContext(), -1, useSelectedColor );
2212 }
2213 }
2214 }
2215}
2216
2218{
2219 QVariantMap map;
2220 if ( !mSvgFilePath.isEmpty() )
2221 {
2222 map.insert( u"svgFile"_s, mSvgFilePath );
2223 }
2224 else
2225 {
2226 map.insert( u"data"_s, QString( mSvgData.toHex() ) );
2227 }
2228
2229 map.insert( u"width"_s, QString::number( mPatternWidth ) );
2230 map.insert( u"angle"_s, QString::number( mAngle ) );
2231
2232 //svg parameters
2233 map.insert( u"color"_s, QgsColorUtils::colorToString( mColor ) );
2234 map.insert( u"outline_color"_s, QgsColorUtils::colorToString( mSvgStrokeColor ) );
2235 map.insert( u"outline_width"_s, QString::number( mSvgStrokeWidth ) );
2236
2237 //units
2238 map.insert( u"pattern_width_unit"_s, QgsUnitTypes::encodeUnit( mPatternWidthUnit ) );
2239 map.insert( u"pattern_width_map_unit_scale"_s, QgsSymbolLayerUtils::encodeMapUnitScale( mPatternWidthMapUnitScale ) );
2240 map.insert( u"svg_outline_width_unit"_s, QgsUnitTypes::encodeUnit( mSvgStrokeWidthUnit ) );
2241 map.insert( u"svg_outline_width_map_unit_scale"_s, QgsSymbolLayerUtils::encodeMapUnitScale( mSvgStrokeWidthMapUnitScale ) );
2242 map.insert( u"outline_width_unit"_s, QgsUnitTypes::encodeUnit( mStrokeWidthUnit ) );
2243 map.insert( u"outline_width_map_unit_scale"_s, QgsSymbolLayerUtils::encodeMapUnitScale( mStrokeWidthMapUnitScale ) );
2244
2245 map[u"parameters"_s] = QgsProperty::propertyMapToVariantMap( mParameters );
2246
2247 return map;
2248}
2249
2251{
2252 std::unique_ptr< QgsSVGFillSymbolLayer > clonedLayer;
2253 if ( !mSvgFilePath.isEmpty() )
2254 {
2255 clonedLayer = std::make_unique< QgsSVGFillSymbolLayer >( mSvgFilePath, mPatternWidth, mAngle );
2256 clonedLayer->setSvgFillColor( mColor );
2257 clonedLayer->setSvgStrokeColor( mSvgStrokeColor );
2258 clonedLayer->setSvgStrokeWidth( mSvgStrokeWidth );
2259 }
2260 else
2261 {
2262 clonedLayer = std::make_unique< QgsSVGFillSymbolLayer >( mSvgData, mPatternWidth, mAngle );
2263 }
2264
2265 clonedLayer->setPatternWidthUnit( mPatternWidthUnit );
2266 clonedLayer->setPatternWidthMapUnitScale( mPatternWidthMapUnitScale );
2267 clonedLayer->setSvgStrokeWidthUnit( mSvgStrokeWidthUnit );
2268 clonedLayer->setSvgStrokeWidthMapUnitScale( mSvgStrokeWidthMapUnitScale );
2269 clonedLayer->setStrokeWidthUnit( mStrokeWidthUnit );
2270 clonedLayer->setStrokeWidthMapUnitScale( mStrokeWidthMapUnitScale );
2271
2272 clonedLayer->setParameters( mParameters );
2273
2274 if ( mStroke )
2275 {
2276 clonedLayer->setSubSymbol( mStroke->clone() );
2277 }
2278 copyCommonProperties( clonedLayer.get() );
2279 return clonedLayer.release();
2280}
2281
2282void QgsSVGFillSymbolLayer::toSld( QDomDocument &doc, QDomElement &element, const QVariantMap &props ) const
2283{
2284 QgsSldExportContext context;
2285 context.setExtraProperties( props );
2286 toSld( doc, element, context );
2287}
2288
2289bool QgsSVGFillSymbolLayer::toSld( QDomDocument &doc, QDomElement &element, QgsSldExportContext &context ) const
2290{
2291 const QVariantMap props = context.extraProperties();
2292 QDomElement symbolizerElem = doc.createElement( u"se:PolygonSymbolizer"_s );
2293 if ( !props.value( u"uom"_s, QString() ).toString().isEmpty() )
2294 symbolizerElem.setAttribute( u"uom"_s, props.value( u"uom"_s, QString() ).toString() );
2295 element.appendChild( symbolizerElem );
2296
2297 QgsSymbolLayerUtils::createGeometryElement( doc, symbolizerElem, props.value( u"geom"_s, QString() ).toString(), context );
2298
2299 QDomElement fillElem = doc.createElement( u"se:Fill"_s );
2300 symbolizerElem.appendChild( fillElem );
2301
2302 QDomElement graphicFillElem = doc.createElement( u"se:GraphicFill"_s );
2303 fillElem.appendChild( graphicFillElem );
2304
2305 QDomElement graphicElem = doc.createElement( u"se:Graphic"_s );
2306 graphicFillElem.appendChild( graphicElem );
2307
2308 if ( !mSvgFilePath.isEmpty() )
2309 {
2310 // encode a parametric SVG reference
2311 double patternWidth = QgsSymbolLayerUtils::rescaleUom( mPatternWidth, mPatternWidthUnit, props );
2312 double strokeWidth = QgsSymbolLayerUtils::rescaleUom( mSvgStrokeWidth, mSvgStrokeWidthUnit, props );
2313 QgsSymbolLayerUtils::parametricSvgToSld( doc, graphicElem, mSvgFilePath, mColor, patternWidth, mSvgStrokeColor, strokeWidth, context );
2314 }
2315 else
2316 {
2317 // TODO: create svg from data
2318 // <se:InlineContent>
2319 // watch out for https://osgeo-org.atlassian.net/browse/GEOT-5206 !
2320 context.pushWarning( QObject::tr( "Exporting embedded SVG content to SLD is not supported" ) );
2321 }
2322
2323 // <Rotation>
2324 QString angleFunc;
2325 bool ok;
2326 double angle = props.value( u"angle"_s, u"0"_s ).toDouble( &ok );
2327 if ( !ok )
2328 {
2329 angleFunc = u"%1 + %2"_s.arg( props.value( u"angle"_s, u"0"_s ).toString() ).arg( mAngle );
2330 }
2331 else if ( !qgsDoubleNear( angle + mAngle, 0.0 ) )
2332 {
2333 angleFunc = QString::number( angle + mAngle );
2334 }
2335 QgsSymbolLayerUtils::createRotationElement( doc, graphicElem, angleFunc, context );
2336
2337 if ( mStroke )
2338 {
2339 // the stroke sub symbol should be stored within the Stroke element,
2340 // but it will be stored in a separated LineSymbolizer because it could
2341 // have more than one layer
2342 mStroke->toSld( doc, element, context );
2343 }
2344 return true;
2345}
2346
2348{
2349 return mPatternWidthUnit == Qgis::RenderUnit::MapUnits
2350 || mPatternWidthUnit == Qgis::RenderUnit::MetersInMapUnits
2351 || mSvgStrokeWidthUnit == Qgis::RenderUnit::MapUnits
2352 || mSvgStrokeWidthUnit == Qgis::RenderUnit::MetersInMapUnits;
2353}
2354
2356{
2357 return mStroke.get();
2358}
2359
2361{
2362 if ( !symbol ) //unset current stroke
2363 {
2364 mStroke.reset( nullptr );
2365 return true;
2366 }
2367
2368 if ( symbol->type() != Qgis::SymbolType::Line )
2369 {
2370 delete symbol;
2371 return false;
2372 }
2373
2374 QgsLineSymbol *lineSymbol = dynamic_cast<QgsLineSymbol *>( symbol );
2375 if ( lineSymbol )
2376 {
2377 mStroke.reset( lineSymbol );
2378 return true;
2379 }
2380
2381 delete symbol;
2382 return false;
2383}
2384
2386{
2387 if ( mStroke && mStroke->symbolLayer( 0 ) )
2388 {
2389 double subLayerBleed = mStroke->symbolLayer( 0 )->estimateMaxBleed( context );
2390 return subLayerBleed;
2391 }
2392 return 0;
2393}
2394
2396{
2397 Q_UNUSED( context )
2398 if ( !mStroke )
2399 {
2400 return QColor( Qt::black );
2401 }
2402 return mStroke->color();
2403}
2404
2405QSet<QString> QgsSVGFillSymbolLayer::usedAttributes( const QgsRenderContext &context ) const
2406{
2407 QSet<QString> attr = QgsImageFillSymbolLayer::usedAttributes( context );
2408 if ( mStroke )
2409 attr.unite( mStroke->usedAttributes( context ) );
2410 return attr;
2411}
2412
2414{
2416 return true;
2417 if ( mStroke && mStroke->hasDataDefinedProperties() )
2418 return true;
2419 return false;
2420}
2421
2422std::unique_ptr<QgsSymbolLayer> QgsSVGFillSymbolLayer::createFromSld( QDomElement &element )
2423{
2424 QString path, mimeType;
2425 QColor fillColor, strokeColor;
2426 Qt::PenStyle penStyle;
2427 double size, strokeWidth;
2428
2429 QDomElement fillElem = element.firstChildElement( u"Fill"_s );
2430 if ( fillElem.isNull() )
2431 return nullptr;
2432
2433 QDomElement graphicFillElem = fillElem.firstChildElement( u"GraphicFill"_s );
2434 if ( graphicFillElem.isNull() )
2435 return nullptr;
2436
2437 QDomElement graphicElem = graphicFillElem.firstChildElement( u"Graphic"_s );
2438 if ( graphicElem.isNull() )
2439 return nullptr;
2440
2441 if ( !QgsSymbolLayerUtils::externalGraphicFromSld( graphicElem, path, mimeType, fillColor, size ) )
2442 return nullptr;
2443
2444 if ( mimeType != "image/svg+xml"_L1 )
2445 return nullptr;
2446
2447 QgsSymbolLayerUtils::lineFromSld( graphicElem, penStyle, strokeColor, strokeWidth );
2448
2449 double scaleFactor = 1.0;
2450 const QString uom = element.attribute( u"uom"_s );
2451 Qgis::RenderUnit sldUnitSize = QgsSymbolLayerUtils::decodeSldUom( uom, &scaleFactor );
2452 size = size * scaleFactor;
2453 strokeWidth = strokeWidth * scaleFactor;
2454
2455 double angle = 0.0;
2456 QString angleFunc;
2457 if ( QgsSymbolLayerUtils::rotationFromSldElement( graphicElem, angleFunc ) )
2458 {
2459 bool ok;
2460 double d = angleFunc.toDouble( &ok );
2461 if ( ok )
2462 angle = d;
2463 }
2464
2465 auto sl = std::make_unique< QgsSVGFillSymbolLayer >( path, size, angle );
2466 sl->setOutputUnit( sldUnitSize );
2467 sl->setSvgFillColor( fillColor );
2468 sl->setSvgStrokeColor( strokeColor );
2469 sl->setSvgStrokeWidth( strokeWidth );
2470
2471 // try to get the stroke
2472 QDomElement strokeElem = element.firstChildElement( u"Stroke"_s );
2473 if ( !strokeElem.isNull() )
2474 {
2475 std::unique_ptr< QgsSymbolLayer > l = QgsSymbolLayerUtils::createLineLayerFromSld( strokeElem );
2476 if ( l )
2477 {
2478 QgsSymbolLayerList layers;
2479 layers.append( l.release() );
2480 sl->setSubSymbol( new QgsLineSymbol( layers ) );
2481 }
2482 }
2483
2484 return sl;
2485}
2486
2488{
2495 {
2496 return; //no data defined settings
2497 }
2498
2500 {
2503 }
2504
2505 double width = mPatternWidth;
2507 {
2508 context.setOriginalValueVariable( mPatternWidth );
2509 width = mDataDefinedProperties.valueAsDouble( QgsSymbolLayer::Property::Width, context.renderContext().expressionContext(), mPatternWidth );
2510 }
2511 QString svgFile = mSvgFilePath;
2513 {
2514 context.setOriginalValueVariable( mSvgFilePath );
2515 svgFile = QgsSymbolLayerUtils::
2517 }
2518 QColor svgFillColor = mColor;
2520 {
2523 }
2524 QColor svgStrokeColor = mSvgStrokeColor;
2526 {
2527 context.setOriginalValueVariable( QgsSymbolLayerUtils::encodeColor( mSvgStrokeColor ) );
2529 }
2530 double strokeWidth = mSvgStrokeWidth;
2532 {
2533 context.setOriginalValueVariable( mSvgStrokeWidth );
2534 strokeWidth = mDataDefinedProperties.valueAsDouble( QgsSymbolLayer::Property::StrokeWidth, context.renderContext().expressionContext(), mSvgStrokeWidth );
2535 }
2536 QgsStringMap evaluatedParameters = QgsSymbolLayerUtils::evaluatePropertiesMap( mParameters, context.renderContext().expressionContext() );
2537
2538 applyPattern( mBrush, svgFile, width, mPatternWidthUnit, svgFillColor, svgStrokeColor, strokeWidth, mSvgStrokeWidthUnit, context, mPatternWidthMapUnitScale, mSvgStrokeWidthMapUnitScale, evaluatedParameters );
2539}
2540
2541void QgsSVGFillSymbolLayer::storeViewBox()
2542{
2543 if ( !mSvgData.isEmpty() )
2544 {
2545 QSvgRenderer r( mSvgData );
2546 if ( r.isValid() )
2547 {
2548 mSvgViewBox = r.viewBoxF();
2549 return;
2550 }
2551 }
2552
2553 mSvgViewBox = QRectF();
2554}
2555
2556void QgsSVGFillSymbolLayer::setDefaultSvgParams()
2557{
2558 if ( mSvgFilePath.isEmpty() )
2559 {
2560 return;
2561 }
2562
2563 bool hasFillParam, hasFillOpacityParam, hasStrokeParam, hasStrokeWidthParam, hasStrokeOpacityParam;
2564 bool hasDefaultFillColor, hasDefaultFillOpacity, hasDefaultStrokeColor, hasDefaultStrokeWidth, hasDefaultStrokeOpacity;
2565 QColor defaultFillColor, defaultStrokeColor;
2566 double defaultStrokeWidth, defaultFillOpacity, defaultStrokeOpacity;
2568 mSvgFilePath,
2569 hasFillParam,
2570 hasDefaultFillColor,
2571 defaultFillColor,
2572 hasFillOpacityParam,
2573 hasDefaultFillOpacity,
2574 defaultFillOpacity,
2575 hasStrokeParam,
2576 hasDefaultStrokeColor,
2577 defaultStrokeColor,
2578 hasStrokeWidthParam,
2579 hasDefaultStrokeWidth,
2580 defaultStrokeWidth,
2581 hasStrokeOpacityParam,
2582 hasDefaultStrokeOpacity,
2583 defaultStrokeOpacity
2584 );
2585
2586 double newFillOpacity = hasFillOpacityParam ? mColor.alphaF() : 1.0;
2587 double newStrokeOpacity = hasStrokeOpacityParam ? mSvgStrokeColor.alphaF() : 1.0;
2588
2589 if ( hasDefaultFillColor )
2590 {
2591 mColor = defaultFillColor;
2592 mColor.setAlphaF( newFillOpacity );
2593 }
2594 if ( hasDefaultFillOpacity )
2595 {
2596 mColor.setAlphaF( defaultFillOpacity );
2597 }
2598 if ( hasDefaultStrokeColor )
2599 {
2600 mSvgStrokeColor = defaultStrokeColor;
2601 mSvgStrokeColor.setAlphaF( newStrokeOpacity );
2602 }
2603 if ( hasDefaultStrokeOpacity )
2604 {
2605 mSvgStrokeColor.setAlphaF( defaultStrokeOpacity );
2606 }
2607 if ( hasDefaultStrokeWidth )
2608 {
2609 mSvgStrokeWidth = defaultStrokeWidth;
2610 }
2611}
2612
2613void QgsSVGFillSymbolLayer::setParameters( const QMap<QString, QgsProperty> &parameters )
2614{
2615 mParameters = parameters;
2616}
2617
2618
2621{
2622 mFillLineSymbol = std::make_unique<QgsLineSymbol>();
2623 QgsImageFillSymbolLayer::setSubSymbol( nullptr ); //no stroke
2624}
2625
2627
2629{
2630 mFillLineSymbol->setWidth( w );
2631 mLineWidth = w;
2632}
2633
2635{
2636 mFillLineSymbol->setColor( c );
2637 mColor = c;
2638}
2639
2641{
2642 return mFillLineSymbol ? mFillLineSymbol->color() : mColor;
2643}
2644
2646{
2647 if ( !symbol )
2648 {
2649 return false;
2650 }
2651
2652 if ( symbol->type() == Qgis::SymbolType::Line )
2653 {
2654 mFillLineSymbol.reset( qgis::down_cast<QgsLineSymbol *>( symbol ) );
2655 return true;
2656 }
2657 delete symbol;
2658 return false;
2659}
2660
2662{
2663 return mFillLineSymbol.get();
2664}
2665
2667{
2668 QSet<QString> attr = QgsImageFillSymbolLayer::usedAttributes( context );
2669 if ( mFillLineSymbol )
2670 attr.unite( mFillLineSymbol->usedAttributes( context ) );
2671 return attr;
2672}
2673
2675{
2677 return true;
2678 if ( mFillLineSymbol && mFillLineSymbol->hasDataDefinedProperties() )
2679 return true;
2680 return false;
2681}
2682
2684{
2685 installMasks( context, true );
2686
2687 // The base class version passes this on to the subsymbol, but we deliberately don't do that here.
2688}
2689
2691{
2692 removeMasks( context, true );
2693
2694 // The base class version passes this on to the subsymbol, but we deliberately don't do that here.
2695}
2696
2698{
2699 double lineAngleRad { qDegreesToRadians( mLineAngle ) };
2700
2701 const int quadrant { static_cast<int>( lineAngleRad / M_PI_2 ) };
2702 Q_ASSERT( quadrant >= 0 && quadrant <= 3 );
2703
2704 switch ( quadrant )
2705 {
2706 case 0:
2707 {
2708 break;
2709 }
2710 case 1:
2711 {
2712 lineAngleRad -= M_PI / 2;
2713 break;
2714 }
2715 case 2:
2716 {
2717 lineAngleRad -= M_PI;
2718 break;
2719 }
2720 case 3:
2721 {
2722 lineAngleRad -= M_PI + M_PI_2;
2723 break;
2724 }
2725 }
2726
2727
2728 double distancePx { QgsSymbolLayerUtils::rescaleUom( mDistance, mDistanceUnit, {} ) };
2729
2730 QSize size { static_cast<int>( distancePx ), static_cast<int>( distancePx ) };
2731
2732 if ( static_cast<int>( mLineAngle ) % 90 != 0 )
2733 {
2734 size = QSize( static_cast<int>( distancePx / std::sin( lineAngleRad ) ), static_cast<int>( distancePx / std::cos( lineAngleRad ) ) );
2735 }
2736
2737 QPixmap pixmap( size );
2738 pixmap.fill( Qt::transparent );
2739 QPainter painter;
2740 painter.begin( &pixmap );
2741 painter.setRenderHint( QPainter::Antialiasing );
2742 QgsRenderContext renderContext = QgsRenderContext::fromQPainter( &painter );
2747 QgsSymbolRenderContext symbolContext( renderContext, Qgis::RenderUnit::Pixels, 1.0, false, Qgis::SymbolRenderHints() );
2748
2749 std::unique_ptr< QgsLinePatternFillSymbolLayer > layerClone( clone() );
2750 layerClone->setOffset( 0 );
2751 layerClone->drawPreviewIcon( symbolContext, pixmap.size() );
2752 painter.end();
2753 return pixmap.toImage();
2754}
2755
2757{
2758 return 0;
2759}
2760
2762{
2764 mDistanceUnit = unit;
2765 mLineWidthUnit = unit;
2766 mOffsetUnit = unit;
2767
2768 if ( mFillLineSymbol )
2769 mFillLineSymbol->setOutputUnit( unit );
2770}
2771
2773{
2775 if ( mDistanceUnit != unit || mLineWidthUnit != unit || ( mOffsetUnit != unit && mOffsetUnit != Qgis::RenderUnit::Percentage ) )
2776 {
2778 }
2779 return unit;
2780}
2781
2783{
2784 return mDistanceUnit == Qgis::RenderUnit::MapUnits
2785 || mDistanceUnit == Qgis::RenderUnit::MetersInMapUnits
2786 || mLineWidthUnit == Qgis::RenderUnit::MapUnits
2787 || mLineWidthUnit == Qgis::RenderUnit::MetersInMapUnits
2788 || mOffsetUnit == Qgis::RenderUnit::MapUnits
2789 || mOffsetUnit == Qgis::RenderUnit::MetersInMapUnits;
2790}
2791
2793{
2795 mDistanceMapUnitScale = scale;
2796 mLineWidthMapUnitScale = scale;
2797 mOffsetMapUnitScale = scale;
2798}
2799
2801{
2802 if ( QgsImageFillSymbolLayer::mapUnitScale() == mDistanceMapUnitScale && mDistanceMapUnitScale == mLineWidthMapUnitScale && mLineWidthMapUnitScale == mOffsetMapUnitScale )
2803 {
2804 return mDistanceMapUnitScale;
2805 }
2806 return QgsMapUnitScale();
2807}
2808
2809std::unique_ptr<QgsSymbolLayer> QgsLinePatternFillSymbolLayer::create( const QVariantMap &properties )
2810{
2811 auto patternLayer = std::make_unique< QgsLinePatternFillSymbolLayer >();
2812
2813 //default values
2814 double lineAngle = 45;
2815 double distance = 5;
2816 double lineWidth = 0.5;
2817 QColor color( Qt::black );
2818 double offset = 0.0;
2819
2820 if ( properties.contains( u"lineangle"_s ) )
2821 {
2822 //pre 2.5 projects used "lineangle"
2823 lineAngle = properties[u"lineangle"_s].toDouble();
2824 }
2825 else if ( properties.contains( u"angle"_s ) )
2826 {
2827 lineAngle = properties[u"angle"_s].toDouble();
2828 }
2829 patternLayer->setLineAngle( lineAngle );
2830
2831 if ( properties.contains( u"distance"_s ) )
2832 {
2833 distance = properties[u"distance"_s].toDouble();
2834 }
2835 patternLayer->setDistance( distance );
2836
2837 if ( properties.contains( u"linewidth"_s ) )
2838 {
2839 //pre 2.5 projects used "linewidth"
2840 lineWidth = properties[u"linewidth"_s].toDouble();
2841 }
2842 else if ( properties.contains( u"outline_width"_s ) )
2843 {
2844 lineWidth = properties[u"outline_width"_s].toDouble();
2845 }
2846 else if ( properties.contains( u"line_width"_s ) )
2847 {
2848 lineWidth = properties[u"line_width"_s].toDouble();
2849 }
2850 patternLayer->setLineWidth( lineWidth );
2851
2852 if ( properties.contains( u"color"_s ) )
2853 {
2854 color = QgsColorUtils::colorFromString( properties[u"color"_s].toString() );
2855 }
2856 else if ( properties.contains( u"outline_color"_s ) )
2857 {
2858 color = QgsColorUtils::colorFromString( properties[u"outline_color"_s].toString() );
2859 }
2860 else if ( properties.contains( u"line_color"_s ) )
2861 {
2862 color = QgsColorUtils::colorFromString( properties[u"line_color"_s].toString() );
2863 }
2864 patternLayer->setColor( color );
2865
2866 if ( properties.contains( u"offset"_s ) )
2867 {
2868 offset = properties[u"offset"_s].toDouble();
2869 }
2870 patternLayer->setOffset( offset );
2871
2872
2873 if ( properties.contains( u"distance_unit"_s ) )
2874 {
2875 patternLayer->setDistanceUnit( QgsUnitTypes::decodeRenderUnit( properties[u"distance_unit"_s].toString() ) );
2876 }
2877 if ( properties.contains( u"distance_map_unit_scale"_s ) )
2878 {
2879 patternLayer->setDistanceMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( properties[u"distance_map_unit_scale"_s].toString() ) );
2880 }
2881 if ( properties.contains( u"line_width_unit"_s ) )
2882 {
2883 patternLayer->setLineWidthUnit( QgsUnitTypes::decodeRenderUnit( properties[u"line_width_unit"_s].toString() ) );
2884 }
2885 else if ( properties.contains( u"outline_width_unit"_s ) )
2886 {
2887 patternLayer->setLineWidthUnit( QgsUnitTypes::decodeRenderUnit( properties[u"outline_width_unit"_s].toString() ) );
2888 }
2889 if ( properties.contains( u"line_width_map_unit_scale"_s ) )
2890 {
2891 patternLayer->setLineWidthMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( properties[u"line_width_map_unit_scale"_s].toString() ) );
2892 }
2893 if ( properties.contains( u"offset_unit"_s ) )
2894 {
2895 patternLayer->setOffsetUnit( QgsUnitTypes::decodeRenderUnit( properties[u"offset_unit"_s].toString() ) );
2896 }
2897 if ( properties.contains( u"offset_map_unit_scale"_s ) )
2898 {
2899 patternLayer->setOffsetMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( properties[u"offset_map_unit_scale"_s].toString() ) );
2900 }
2901 if ( properties.contains( u"outline_width_unit"_s ) )
2902 {
2903 patternLayer->setStrokeWidthUnit( QgsUnitTypes::decodeRenderUnit( properties[u"outline_width_unit"_s].toString() ) );
2904 }
2905 if ( properties.contains( u"outline_width_map_unit_scale"_s ) )
2906 {
2907 patternLayer->setStrokeWidthMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( properties[u"outline_width_map_unit_scale"_s].toString() ) );
2908 }
2909 if ( properties.contains( u"coordinate_reference"_s ) )
2910 {
2911 patternLayer->setCoordinateReference( QgsSymbolLayerUtils::decodeCoordinateReference( properties[u"coordinate_reference"_s].toString() ) );
2912 }
2913 if ( properties.contains( u"clip_mode"_s ) )
2914 {
2915 patternLayer->setClipMode( QgsSymbolLayerUtils::decodeLineClipMode( properties.value( u"clip_mode"_s ).toString() ) );
2916 }
2917
2918 patternLayer->restoreOldDataDefinedProperties( properties );
2919
2920 return patternLayer;
2921}
2922
2924{
2925 return u"LinePatternFill"_s;
2926}
2927
2928bool QgsLinePatternFillSymbolLayer::applyPattern( const QgsSymbolRenderContext &context, QBrush &brush, double lineAngle, double distance )
2929{
2930 mBrush.setTextureImage( QImage() ); // set empty in case we have to return
2931
2932 if ( !mFillLineSymbol )
2933 {
2934 return true;
2935 }
2936 // We have to make a copy because marker intervals will have to be adjusted
2937 std::unique_ptr< QgsLineSymbol > fillLineSymbol( mFillLineSymbol->clone() );
2938 if ( !fillLineSymbol )
2939 {
2940 return true;
2941 }
2942
2943 const QgsRenderContext &ctx = context.renderContext();
2944 //double strokePixelWidth = lineWidth * QgsSymbolLayerUtils::pixelSizeScaleFactor( ctx, mLineWidthUnit, mLineWidthMapUnitScale );
2945 double outputPixelDist = ctx.convertToPainterUnits( distance, mDistanceUnit, mDistanceMapUnitScale );
2946 double outputPixelOffset = mOffsetUnit == Qgis::RenderUnit::Percentage ? outputPixelDist * mOffset / 100 : ctx.convertToPainterUnits( mOffset, mOffsetUnit, mOffsetMapUnitScale );
2947
2948 // NOTE: this may need to be modified if we ever change from a forced rasterized/brush approach,
2949 // because potentially we may want to allow vector based line pattern fills where the first line
2950 // is offset by a large distance
2951
2952 // fix truncated pattern with larger offsets
2953 outputPixelOffset = std::fmod( outputPixelOffset, outputPixelDist );
2954 if ( outputPixelOffset > outputPixelDist / 2.0 )
2955 outputPixelOffset -= outputPixelDist;
2956
2957 // To get all patterns into image, we have to consider symbols size (estimateMaxBleed()).
2958 // For marker lines we have to get markers interval.
2959 double outputPixelBleed = 0;
2960 double outputPixelInterval = 0; // maximum interval
2961 for ( int i = 0; i < fillLineSymbol->symbolLayerCount(); i++ )
2962 {
2963 QgsSymbolLayer *layer = fillLineSymbol->symbolLayer( i );
2964 double outputPixelLayerBleed = layer->estimateMaxBleed( context.renderContext() );
2965 outputPixelBleed = std::max( outputPixelBleed, outputPixelLayerBleed );
2966
2967 QgsMarkerLineSymbolLayer *markerLineLayer = dynamic_cast<QgsMarkerLineSymbolLayer *>( layer );
2968 if ( markerLineLayer )
2969 {
2970 double outputPixelLayerInterval = ctx.convertToPainterUnits( markerLineLayer->interval(), markerLineLayer->intervalUnit(), markerLineLayer->intervalMapUnitScale() );
2971
2972 // There may be multiple marker lines with different intervals.
2973 // In theory we should find the least common multiple, but that could be too
2974 // big (multiplication of intervals in the worst case).
2975 // Because patterns without small common interval would look strange, we
2976 // believe that the longest interval should usually be sufficient.
2977 outputPixelInterval = std::max( outputPixelInterval, outputPixelLayerInterval );
2978 }
2979 }
2980
2981 if ( outputPixelInterval > 0 )
2982 {
2983 // We have to adjust marker intervals to integer pixel size to get
2984 // repeatable pattern.
2985 double intervalScale = std::round( outputPixelInterval ) / outputPixelInterval;
2986 outputPixelInterval = std::round( outputPixelInterval );
2987
2988 for ( int i = 0; i < fillLineSymbol->symbolLayerCount(); i++ )
2989 {
2990 QgsSymbolLayer *layer = fillLineSymbol->symbolLayer( i );
2991
2992 QgsMarkerLineSymbolLayer *markerLineLayer = dynamic_cast<QgsMarkerLineSymbolLayer *>( layer );
2993 if ( markerLineLayer )
2994 {
2995 markerLineLayer->setInterval( intervalScale * markerLineLayer->interval() );
2996 }
2997 }
2998 }
2999
3000 //create image
3001 int height, width;
3002 lineAngle = std::fmod( lineAngle, 360 );
3003 if ( lineAngle < 0 )
3004 lineAngle += 360;
3005 if ( qgsDoubleNear( lineAngle, 0 ) || qgsDoubleNear( lineAngle, 360 ) || qgsDoubleNear( lineAngle, 180 ) )
3006 {
3007 height = outputPixelDist;
3008 width = outputPixelInterval > 0 ? outputPixelInterval : height;
3009 }
3010 else if ( qgsDoubleNear( lineAngle, 90 ) || qgsDoubleNear( lineAngle, 270 ) )
3011 {
3012 width = outputPixelDist;
3013 height = outputPixelInterval > 0 ? outputPixelInterval : width;
3014 }
3015 else
3016 {
3017 height = outputPixelDist / std::cos( lineAngle * M_PI / 180 ); //keep perpendicular distance between lines constant
3018 width = outputPixelDist / std::sin( lineAngle * M_PI / 180 );
3019
3020 // recalculate real angle and distance after rounding to pixels
3021 lineAngle = 180 * std::atan2( static_cast< double >( height ), static_cast< double >( width ) ) / M_PI;
3022 if ( lineAngle < 0 )
3023 {
3024 lineAngle += 360.;
3025 }
3026
3027 height = std::abs( height );
3028 width = std::abs( width );
3029
3030 outputPixelDist = std::abs( height * std::cos( lineAngle * M_PI / 180 ) );
3031
3032 // Round offset to correspond to one pixel height, otherwise lines may
3033 // be shifted on tile border if offset falls close to pixel center
3034 int offsetHeight = static_cast< int >( std::round( outputPixelOffset / std::cos( lineAngle * M_PI / 180 ) ) );
3035 outputPixelOffset = offsetHeight * std::cos( lineAngle * M_PI / 180 );
3036 }
3037
3038 //depending on the angle, we might need to render into a larger image and use a subset of it
3039 double dx = 0;
3040 double dy = 0;
3041
3042 // Add buffer based on bleed but keep precisely the height/width ratio (angle)
3043 // thus we add integer multiplications of width and height covering the bleed
3044 int bufferMulti = static_cast< int >( std::max( std::ceil( outputPixelBleed / width ), std::ceil( outputPixelBleed / width ) ) );
3045
3046 // Always buffer at least once so that center of line marker in upper right corner
3047 // does not fall outside due to representation error
3048 bufferMulti = std::max( bufferMulti, 1 );
3049
3050 int xBuffer = width * bufferMulti;
3051 int yBuffer = height * bufferMulti;
3052 int innerWidth = width;
3053 int innerHeight = height;
3054 width += 2 * xBuffer;
3055 height += 2 * yBuffer;
3056
3057 //protect from zero width/height image and symbol layer from eating too much memory
3058 if ( width > 2000 || height > 2000 || width == 0 || height == 0 )
3059 {
3060 return false;
3061 }
3062
3063 QImage patternImage( width, height, QImage::Format_ARGB32 );
3064 patternImage.fill( 0 );
3065
3066 QPointF p1, p2, p3, p4, p5, p6;
3067 if ( qgsDoubleNear( lineAngle, 0.0 ) || qgsDoubleNear( lineAngle, 360.0 ) || qgsDoubleNear( lineAngle, 180.0 ) )
3068 {
3069 p1 = QPointF( 0, yBuffer );
3070 p2 = QPointF( width, yBuffer );
3071 p3 = QPointF( 0, yBuffer + innerHeight );
3072 p4 = QPointF( width, yBuffer + innerHeight );
3073 }
3074 else if ( qgsDoubleNear( lineAngle, 90.0 ) || qgsDoubleNear( lineAngle, 270.0 ) )
3075 {
3076 p1 = QPointF( xBuffer, height );
3077 p2 = QPointF( xBuffer, 0 );
3078 p3 = QPointF( xBuffer + innerWidth, height );
3079 p4 = QPointF( xBuffer + innerWidth, 0 );
3080 }
3081 else if ( lineAngle > 0 && lineAngle < 90 )
3082 {
3083 dx = outputPixelDist * std::cos( ( 90 - lineAngle ) * M_PI / 180.0 );
3084 dy = outputPixelDist * std::sin( ( 90 - lineAngle ) * M_PI / 180.0 );
3085 p1 = QPointF( 0, height );
3086 p2 = QPointF( width, 0 );
3087 p3 = QPointF( -dx, height - dy );
3088 p4 = QPointF( width - dx, -dy );
3089 p5 = QPointF( dx, height + dy );
3090 p6 = QPointF( width + dx, dy );
3091 }
3092 else if ( lineAngle > 180 && lineAngle < 270 )
3093 {
3094 dx = outputPixelDist * std::cos( ( 90 - lineAngle ) * M_PI / 180.0 );
3095 dy = outputPixelDist * std::sin( ( 90 - lineAngle ) * M_PI / 180.0 );
3096 p1 = QPointF( width, 0 );
3097 p2 = QPointF( 0, height );
3098 p3 = QPointF( width - dx, -dy );
3099 p4 = QPointF( -dx, height - dy );
3100 p5 = QPointF( width + dx, dy );
3101 p6 = QPointF( dx, height + dy );
3102 }
3103 else if ( lineAngle > 90 && lineAngle < 180 )
3104 {
3105 dy = outputPixelDist * std::cos( ( 180 - lineAngle ) * M_PI / 180 );
3106 dx = outputPixelDist * std::sin( ( 180 - lineAngle ) * M_PI / 180 );
3107 p1 = QPointF( 0, 0 );
3108 p2 = QPointF( width, height );
3109 p5 = QPointF( dx, -dy );
3110 p6 = QPointF( width + dx, height - dy );
3111 p3 = QPointF( -dx, dy );
3112 p4 = QPointF( width - dx, height + dy );
3113 }
3114 else if ( lineAngle > 270 && lineAngle < 360 )
3115 {
3116 dy = outputPixelDist * std::cos( ( 180 - lineAngle ) * M_PI / 180 );
3117 dx = outputPixelDist * std::sin( ( 180 - lineAngle ) * M_PI / 180 );
3118 p1 = QPointF( width, height );
3119 p2 = QPointF( 0, 0 );
3120 p5 = QPointF( width + dx, height - dy );
3121 p6 = QPointF( dx, -dy );
3122 p3 = QPointF( width - dx, height + dy );
3123 p4 = QPointF( -dx, dy );
3124 }
3125
3126 if ( !qgsDoubleNear( mOffset, 0.0 ) ) //shift everything
3127 {
3128 QPointF tempPt;
3129 tempPt = QgsSymbolLayerUtils::pointOnLineWithDistance( p1, p3, outputPixelDist + outputPixelOffset );
3130 p3 = QPointF( tempPt.x(), tempPt.y() );
3131 tempPt = QgsSymbolLayerUtils::pointOnLineWithDistance( p2, p4, outputPixelDist + outputPixelOffset );
3132 p4 = QPointF( tempPt.x(), tempPt.y() );
3133 tempPt = QgsSymbolLayerUtils::pointOnLineWithDistance( p1, p5, outputPixelDist - outputPixelOffset );
3134 p5 = QPointF( tempPt.x(), tempPt.y() );
3135 tempPt = QgsSymbolLayerUtils::pointOnLineWithDistance( p2, p6, outputPixelDist - outputPixelOffset );
3136 p6 = QPointF( tempPt.x(), tempPt.y() );
3137
3138 //update p1, p2 last
3139 tempPt = QgsSymbolLayerUtils::pointOnLineWithDistance( p1, p3, outputPixelOffset );
3140 p1 = QPointF( tempPt.x(), tempPt.y() );
3141 tempPt = QgsSymbolLayerUtils::pointOnLineWithDistance( p2, p4, outputPixelOffset );
3142 p2 = QPointF( tempPt.x(), tempPt.y() );
3143 }
3144
3145 QPainter p( &patternImage );
3146
3147#if 0
3148 // DEBUG: Draw rectangle
3149 p.setRenderHint( QPainter::Antialiasing, false ); // get true rect
3150 QPen pen( QColor( Qt::black ) );
3151 pen.setWidthF( 0.1 );
3152 pen.setCapStyle( Qt::FlatCap );
3153 p.setPen( pen );
3154
3155 // To see this rectangle, comment buffer cut below.
3156 // Subtract 1 because not antialiased are rendered to the right/down by 1 pixel
3157 QPolygon polygon = QPolygon() << QPoint( 0, 0 ) << QPoint( width - 1, 0 ) << QPoint( width - 1, height - 1 ) << QPoint( 0, height - 1 ) << QPoint( 0, 0 );
3158 p.drawPolygon( polygon );
3159
3160 polygon = QPolygon() << QPoint( xBuffer, yBuffer ) << QPoint( width - xBuffer - 1, yBuffer ) << QPoint( width - xBuffer - 1, height - yBuffer - 1 ) << QPoint( xBuffer, height - yBuffer - 1 ) << QPoint( xBuffer, yBuffer );
3161 p.drawPolygon( polygon );
3162#endif
3163
3164 // Use antialiasing because without antialiasing lines are rendered to the
3165 // right and below the mathematically defined points (not symmetrical)
3166 // and such tiles become useless for are filling
3167 p.setRenderHint( QPainter::Antialiasing, true );
3168
3169 // line rendering needs context for drawing on patternImage
3170 QgsRenderContext lineRenderContext;
3171 lineRenderContext.setPainter( &p );
3172 lineRenderContext.setScaleFactor( context.renderContext().scaleFactor() );
3173 QgsMapToPixel mtp( context.renderContext().mapToPixel().mapUnitsPerPixel() );
3174 lineRenderContext.setMapToPixel( mtp );
3175 lineRenderContext.setExpressionContext( context.renderContext().expressionContext() );
3177 lineRenderContext.setDisabledSymbolLayersV2( context.renderContext().disabledSymbolLayersV2() );
3178
3179 fillLineSymbol->setRenderHints( fillLineSymbol->renderHints() | Qgis::SymbolRenderHint::IsSymbolLayerSubSymbol );
3180 fillLineSymbol->startRender( lineRenderContext, context.fields() );
3181
3182 QVector<QPolygonF> polygons;
3183 polygons.append( QPolygonF() << p1 << p2 );
3184 polygons.append( QPolygonF() << p3 << p4 );
3185 if ( !qgsDoubleNear( lineAngle, 0 ) && !qgsDoubleNear( lineAngle, 360 ) && !qgsDoubleNear( lineAngle, 90 ) && !qgsDoubleNear( lineAngle, 180 ) && !qgsDoubleNear( lineAngle, 270 ) )
3186 {
3187 polygons.append( QPolygonF() << p5 << p6 );
3188 }
3189
3190 const bool useSelectedColor = shouldRenderUsingSelectionColor( context );
3191 for ( const QPolygonF &polygon : std::as_const( polygons ) )
3192 {
3193 fillLineSymbol->renderPolyline( polygon, context.feature(), lineRenderContext, -1, useSelectedColor );
3194 }
3195
3196 fillLineSymbol->stopRender( lineRenderContext );
3197 p.end();
3198
3199 // Cut off the buffer
3200 patternImage = patternImage.copy( xBuffer, yBuffer, patternImage.width() - 2 * xBuffer, patternImage.height() - 2 * yBuffer );
3201
3202 //set image to mBrush
3203 if ( !qgsDoubleNear( context.opacity(), 1.0 ) )
3204 {
3205 QImage transparentImage = patternImage.copy();
3206 QgsSymbolLayerUtils::multiplyImageOpacity( &transparentImage, context.opacity() );
3207 brush.setTextureImage( transparentImage );
3208 }
3209 else
3210 {
3211 brush.setTextureImage( patternImage );
3212 }
3213
3214 QTransform brushTransform;
3215 brush.setTransform( brushTransform );
3216
3217 return true;
3218}
3219
3221{
3222 // if we are using a vector based output, we need to render points as vectors
3223 // (OR if the line has data defined symbology, in which case we need to evaluate this line-by-line)
3224 mRenderUsingLines = context.forceVectorRendering()
3225 || ( mFillLineSymbol && mFillLineSymbol->hasDataDefinedProperties() )
3228
3229 if ( !mRenderUsingLines )
3230 {
3231 // optimised render for screen only, use image based brush
3232 // (fallback to line rendering when pattern image will result in too large a memory footprint)
3233 mRenderUsingLines = !applyPattern( context, mBrush, mLineAngle, mDistance );
3234 }
3235
3236 if ( mRenderUsingLines && mFillLineSymbol )
3237 {
3238 mFillLineSymbol->setRenderHints( mFillLineSymbol->renderHints() | Qgis::SymbolRenderHint::IsSymbolLayerSubSymbol );
3239 mFillLineSymbol->startRender( context.renderContext(), context.fields() );
3240 mFillLineSymbolRenderStarted = true;
3241 }
3242}
3243
3245{
3246 if ( mFillLineSymbolRenderStarted )
3247 {
3248 mFillLineSymbol->stopRender( context.renderContext() );
3249 mFillLineSymbolRenderStarted = false;
3250 }
3251}
3252
3253void QgsLinePatternFillSymbolLayer::renderPolygon( const QPolygonF &points, const QVector<QPolygonF> *rings, QgsSymbolRenderContext &context )
3254{
3255 const bool useSelectedColor = shouldRenderUsingSelectionColor( context );
3256 if ( !useSelectedColor && !mRenderUsingLines )
3257 {
3258 // use image based brush for speed
3259 QgsImageFillSymbolLayer::renderPolygon( points, rings, context );
3260 return;
3261 }
3262
3263 if ( !mFillLineSymbol )
3264 return;
3265
3266 if ( !mFillLineSymbolRenderStarted )
3267 {
3268 mFillLineSymbol->setRenderHints( mFillLineSymbol->renderHints() | Qgis::SymbolRenderHint::IsSymbolLayerSubSymbol );
3269 mFillLineSymbol->startRender( context.renderContext(), context.fields() );
3270 mFillLineSymbolRenderStarted = true;
3271 }
3272
3273 // vector based output - so draw line by line!
3274 QPainter *p = context.renderContext().painter();
3275 if ( !p )
3276 {
3277 return;
3278 }
3279
3280 double lineAngle = mLineAngle;
3282 {
3283 context.setOriginalValueVariable( mLineAngle );
3285 }
3286
3287 double distance = mDistance;
3289 {
3290 context.setOriginalValueVariable( mDistance );
3292 }
3293 // Clip distance to a reasonable distance to avoid app freezes
3294 double outputPixelDistance = context.renderContext().convertToPainterUnits( distance, mDistanceUnit, mDistanceMapUnitScale );
3295
3296 double offset = mOffset;
3297 double outputPixelOffset = mOffsetUnit == Qgis::RenderUnit::Percentage ? outputPixelDistance * offset / 100 : context.renderContext().convertToPainterUnits( offset, mOffsetUnit, mOffsetMapUnitScale );
3298
3299 // fix truncated pattern with larger offsets
3300 outputPixelOffset = std::fmod( outputPixelOffset, outputPixelDistance );
3301 if ( outputPixelOffset > outputPixelDistance / 2.0 )
3302 outputPixelOffset -= outputPixelDistance;
3303
3304 p->setPen( QPen( Qt::NoPen ) );
3305
3306 // if invalid parameters, skip out
3307 if ( qgsDoubleNear( distance, 0 ) )
3308 return;
3309
3310 // Clip distance to a reasonable distance to avoid app freezes
3311 outputPixelDistance = std::max( ( context.renderContext().flags() & Qgis::RenderContextFlag::RenderLayerTree ) ? 0.1 : 0.025, outputPixelDistance );
3312
3313 QgsScopedQPainterState painterState( p );
3314
3315 Qgis::LineClipMode clipMode = mClipMode;
3317 {
3319 bool ok = false;
3320 const QString valueString = mDataDefinedProperties.valueAsString( QgsSymbolLayer::Property::LineClipping, context.renderContext().expressionContext(), QString(), &ok );
3321 if ( ok )
3322 {
3323 Qgis::LineClipMode decodedMode = QgsSymbolLayerUtils::decodeLineClipMode( valueString, &ok );
3324 if ( ok )
3325 clipMode = decodedMode;
3326 }
3327 }
3328
3329 std::unique_ptr< QgsPolygon > shapePolygon;
3330 std::unique_ptr< QgsGeometryEngine > shapeEngine;
3331 switch ( clipMode )
3332 {
3334 break;
3335
3337 {
3338 shapePolygon = std::make_unique< QgsPolygon >();
3339 std::unique_ptr< QgsLineString > fromPolygon = QgsLineString::fromQPolygonF( points );
3340 shapePolygon->setExteriorRing( fromPolygon.release() );
3341 if ( rings )
3342 {
3343 for ( const QPolygonF &ring : *rings )
3344 {
3345 std::unique_ptr< QgsLineString > fromRing = QgsLineString::fromQPolygonF( ring );
3346 shapePolygon->addInteriorRing( fromRing.release() );
3347 }
3348 }
3349 shapeEngine = QgsGeometry::createGeometryEngine( shapePolygon.get() );
3350 shapeEngine->prepareGeometry();
3351 break;
3352 }
3353
3355 {
3356 QPainterPath path;
3357 path.addPolygon( points );
3358 if ( rings )
3359 {
3360 for ( const QPolygonF &ring : *rings )
3361 {
3362 path.addPolygon( ring );
3363 }
3364 }
3365 p->setClipPath( path, Qt::IntersectClip );
3366 break;
3367 }
3368 }
3369
3370 const bool applyBrushTransform = applyBrushTransformFromContext( &context );
3371 const QRectF boundingRect = points.boundingRect();
3372
3373 QTransform invertedRotateTransform;
3374 double left;
3375 double top;
3376 double right;
3377 double bottom;
3378
3379 QTransform transform;
3380 if ( applyBrushTransform )
3381 {
3382 // rotation applies around center of feature
3383 transform.translate( -boundingRect.center().x(), -boundingRect.center().y() );
3384 transform.rotate( lineAngle );
3385 transform.translate( boundingRect.center().x(), boundingRect.center().y() );
3386 }
3387 else
3388 {
3389 // rotation applies around top of viewport
3390 transform.rotate( lineAngle );
3391 }
3392
3393 const QRectF transformedBounds = transform.map( points ).boundingRect();
3394
3395 // bounds are expanded out a bit to account for maximum line width
3396 const double buffer = QgsSymbolLayerUtils::estimateMaxSymbolBleed( mFillLineSymbol.get(), context.renderContext() );
3397 left = transformedBounds.left() - buffer * 2;
3398 top = transformedBounds.top() - buffer * 2;
3399 right = transformedBounds.right() + buffer * 2;
3400 bottom = transformedBounds.bottom() + buffer * 2;
3401 invertedRotateTransform = transform.inverted();
3402
3403 if ( !applyBrushTransform )
3404 {
3405 top -= transformedBounds.top() - ( outputPixelDistance * std::floor( transformedBounds.top() / outputPixelDistance ) );
3406 }
3407
3409 QgsExpressionContextScopePopper scopePopper( context.renderContext().expressionContext(), scope );
3410 const bool needsExpressionContext = mFillLineSymbol->hasDataDefinedProperties();
3411
3412 const bool prevIsSubsymbol = context.renderContext().flags() & Qgis::RenderContextFlag::RenderingSubSymbol;
3414
3415 int currentLine = 0;
3416 for ( double currentY = top; currentY <= bottom; currentY += outputPixelDistance )
3417 {
3418 if ( context.renderContext().renderingStopped() )
3419 break;
3420
3421 if ( needsExpressionContext )
3422 scope->addVariable( QgsExpressionContextScope::StaticVariable( u"symbol_line_number"_s, ++currentLine, true ) );
3423
3424 double x1 = left;
3425 double y1 = currentY;
3426 double x2 = left;
3427 double y2 = currentY;
3428 invertedRotateTransform.map( left, currentY - outputPixelOffset, &x1, &y1 );
3429 invertedRotateTransform.map( right, currentY - outputPixelOffset, &x2, &y2 );
3430
3431 if ( shapeEngine )
3432 {
3433 QgsLineString ls( QgsPoint( x1, y1 ), QgsPoint( x2, y2 ) );
3434 std::unique_ptr< QgsAbstractGeometry > intersection( shapeEngine->intersection( &ls, nullptr, QgsGeometryParameters(), context.renderContext().feedback() ) );
3435 for ( auto it = intersection->const_parts_begin(); it != intersection->const_parts_end(); ++it )
3436 {
3438 {
3439 mFillLineSymbol->renderPolyline( ls->asQPolygonF(), context.feature(), context.renderContext(), -1, useSelectedColor );
3440 }
3441 }
3442 }
3443 else
3444 {
3445 mFillLineSymbol->renderPolyline( QPolygonF() << QPointF( x1, y1 ) << QPointF( x2, y2 ), context.feature(), context.renderContext(), -1, useSelectedColor );
3446 }
3447 }
3448
3450}
3451
3453{
3454 QVariantMap map = QgsImageFillSymbolLayer::properties();
3455 map.insert( u"angle"_s, QString::number( mLineAngle ) );
3456 map.insert( u"distance"_s, QString::number( mDistance ) );
3457 map.insert( u"line_width"_s, QString::number( mLineWidth ) );
3458 map.insert( u"color"_s, QgsColorUtils::colorToString( mColor ) );
3459 map.insert( u"offset"_s, QString::number( mOffset ) );
3460 map.insert( u"distance_unit"_s, QgsUnitTypes::encodeUnit( mDistanceUnit ) );
3461 map.insert( u"line_width_unit"_s, QgsUnitTypes::encodeUnit( mLineWidthUnit ) );
3462 map.insert( u"offset_unit"_s, QgsUnitTypes::encodeUnit( mOffsetUnit ) );
3463 map.insert( u"distance_map_unit_scale"_s, QgsSymbolLayerUtils::encodeMapUnitScale( mDistanceMapUnitScale ) );
3464 map.insert( u"line_width_map_unit_scale"_s, QgsSymbolLayerUtils::encodeMapUnitScale( mLineWidthMapUnitScale ) );
3465 map.insert( u"offset_map_unit_scale"_s, QgsSymbolLayerUtils::encodeMapUnitScale( mOffsetMapUnitScale ) );
3466 map.insert( u"outline_width_unit"_s, QgsUnitTypes::encodeUnit( mStrokeWidthUnit ) );
3467 map.insert( u"outline_width_map_unit_scale"_s, QgsSymbolLayerUtils::encodeMapUnitScale( mStrokeWidthMapUnitScale ) );
3468 map.insert( u"clip_mode"_s, QgsSymbolLayerUtils::encodeLineClipMode( mClipMode ) );
3469 return map;
3470}
3471
3473{
3474 auto clonedLayer = qgis::unique_ptr_static_cast<QgsLinePatternFillSymbolLayer>( QgsLinePatternFillSymbolLayer::create( properties() ) );
3475 if ( mFillLineSymbol )
3476 {
3477 clonedLayer->setSubSymbol( mFillLineSymbol->clone() );
3478 }
3479 copyCommonProperties( clonedLayer.get() );
3480 return clonedLayer.release();
3481}
3482
3483void QgsLinePatternFillSymbolLayer::toSld( QDomDocument &doc, QDomElement &element, const QVariantMap &props ) const
3484{
3485 QgsSldExportContext context;
3486 context.setExtraProperties( props );
3487 toSld( doc, element, context );
3488}
3489
3490bool QgsLinePatternFillSymbolLayer::toSld( QDomDocument &doc, QDomElement &element, QgsSldExportContext &context ) const
3491{
3492 const QVariantMap props = context.extraProperties();
3493 QDomElement symbolizerElem = doc.createElement( u"se:PolygonSymbolizer"_s );
3494 if ( !props.value( u"uom"_s, QString() ).toString().isEmpty() )
3495 symbolizerElem.setAttribute( u"uom"_s, props.value( u"uom"_s, QString() ).toString() );
3496 element.appendChild( symbolizerElem );
3497
3498 // <Geometry>
3499 QgsSymbolLayerUtils::createGeometryElement( doc, symbolizerElem, props.value( u"geom"_s, QString() ).toString(), context );
3500
3501 QDomElement fillElem = doc.createElement( u"se:Fill"_s );
3502 symbolizerElem.appendChild( fillElem );
3503
3504 QDomElement graphicFillElem = doc.createElement( u"se:GraphicFill"_s );
3505 fillElem.appendChild( graphicFillElem );
3506
3507 QDomElement graphicElem = doc.createElement( u"se:Graphic"_s );
3508 graphicFillElem.appendChild( graphicElem );
3509
3510 // Export to PNG (TODO: SVG)
3511 bool exportOk { false };
3512 if ( !context.exportFilePath().isEmpty() && context.exportOptions().testFlag( Qgis::SldExportOption::Png ) )
3513 {
3514 const QImage image { toTiledPatternImage() };
3515 if ( !image.isNull() )
3516 {
3517 const QFileInfo info { context.exportFilePath() };
3518 QString pngPath { info.completeSuffix().isEmpty() ? context.exportFilePath() : context.exportFilePath().chopped( info.completeSuffix().length() ).append( u"png"_s ) };
3519 pngPath = QgsFileUtils::uniquePath( pngPath );
3520 image.save( pngPath );
3521 QgsSymbolLayerUtils::externalGraphicToSld( doc, graphicElem, QFileInfo( pngPath ).fileName(), u"image/png"_s, QColor(), image.height() );
3522 exportOk = true;
3523 }
3524 }
3525
3526 if ( !exportOk )
3527 {
3528 //line properties must be inside the graphic definition
3529 QColor lineColor = mFillLineSymbol ? mFillLineSymbol->color() : QColor();
3530 double lineWidth = mFillLineSymbol ? mFillLineSymbol->width() : 0.0;
3531 lineWidth = QgsSymbolLayerUtils::rescaleUom( lineWidth, mLineWidthUnit, props );
3532 double distance = QgsSymbolLayerUtils::rescaleUom( mDistance, mDistanceUnit, props );
3533 QgsSymbolLayerUtils::wellKnownMarkerToSld( doc, graphicElem, u"horline"_s, QColor(), lineColor, Qt::SolidLine, context, lineWidth, distance );
3534
3535 // <Rotation>
3536 QString angleFunc;
3537 bool ok;
3538 double angle = props.value( u"angle"_s, u"0"_s ).toDouble( &ok );
3539 if ( !ok )
3540 {
3541 angleFunc = u"%1 + %2"_s.arg( props.value( u"angle"_s, u"0"_s ).toString() ).arg( mLineAngle );
3542 }
3543 else if ( !qgsDoubleNear( angle + mLineAngle, 0.0 ) )
3544 {
3545 angleFunc = QString::number( angle + mLineAngle );
3546 }
3547 QgsSymbolLayerUtils::createRotationElement( doc, graphicElem, angleFunc, context );
3548
3549 // <se:Displacement>
3550 QPointF lineOffset( std::sin( mLineAngle ) * mOffset, std::cos( mLineAngle ) * mOffset );
3551 lineOffset = QgsSymbolLayerUtils::rescaleUom( lineOffset, mOffsetUnit, props );
3552 QgsSymbolLayerUtils::createDisplacementElement( doc, graphicElem, lineOffset );
3553 }
3554 return true;
3555}
3556
3557QString QgsLinePatternFillSymbolLayer::ogrFeatureStyleWidth( double widthScaleFactor ) const
3558{
3559 QString featureStyle;
3560 featureStyle.append( "Brush(" );
3561 featureStyle.append( u"fc:%1"_s.arg( mColor.name() ) );
3562 featureStyle.append( u",bc:%1"_s.arg( "#00000000"_L1 ) ); //transparent background
3563 featureStyle.append( ",id:\"ogr-brush-2\"" );
3564 featureStyle.append( u",a:%1"_s.arg( mLineAngle ) );
3565 featureStyle.append( u",s:%1"_s.arg( mLineWidth * widthScaleFactor ) );
3566 featureStyle.append( ",dx:0mm" );
3567 featureStyle.append( u",dy:%1mm"_s.arg( mDistance * widthScaleFactor ) );
3568 featureStyle.append( ')' );
3569 return featureStyle;
3570}
3571
3573{
3576 && ( !mFillLineSymbol || !mFillLineSymbol->hasDataDefinedProperties() ) )
3577 {
3578 return; //no data defined settings
3579 }
3580
3581 double lineAngle = mLineAngle;
3583 {
3584 context.setOriginalValueVariable( mLineAngle );
3586 }
3587 double distance = mDistance;
3589 {
3590 context.setOriginalValueVariable( mDistance );
3592 }
3593 applyPattern( context, mBrush, lineAngle, distance );
3594}
3595
3596std::unique_ptr<QgsSymbolLayer> QgsLinePatternFillSymbolLayer::createFromSld( QDomElement &element )
3597{
3598 QString name;
3599 QColor fillColor, lineColor;
3600 double size, lineWidth;
3601 Qt::PenStyle lineStyle;
3602
3603 QDomElement fillElem = element.firstChildElement( u"Fill"_s );
3604 if ( fillElem.isNull() )
3605 return nullptr;
3606
3607 QDomElement graphicFillElem = fillElem.firstChildElement( u"GraphicFill"_s );
3608 if ( graphicFillElem.isNull() )
3609 return nullptr;
3610
3611 QDomElement graphicElem = graphicFillElem.firstChildElement( u"Graphic"_s );
3612 if ( graphicElem.isNull() )
3613 return nullptr;
3614
3615 if ( !QgsSymbolLayerUtils::wellKnownMarkerFromSld( graphicElem, name, fillColor, lineColor, lineStyle, lineWidth, size ) )
3616 return nullptr;
3617
3618 if ( name != "horline"_L1 )
3619 return nullptr;
3620
3621 double angle = 0.0;
3622 QString angleFunc;
3623 if ( QgsSymbolLayerUtils::rotationFromSldElement( graphicElem, angleFunc ) )
3624 {
3625 bool ok;
3626 double d = angleFunc.toDouble( &ok );
3627 if ( ok )
3628 angle = d;
3629 }
3630
3631 double offset = 0.0;
3632 QPointF vectOffset;
3633 if ( QgsSymbolLayerUtils::displacementFromSldElement( graphicElem, vectOffset ) )
3634 {
3635 offset = std::sqrt( std::pow( vectOffset.x(), 2 ) + std::pow( vectOffset.y(), 2 ) );
3636 }
3637
3638 double scaleFactor = 1.0;
3639 const QString uom = element.attribute( u"uom"_s );
3640 Qgis::RenderUnit sldUnitSize = QgsSymbolLayerUtils::decodeSldUom( uom, &scaleFactor );
3641 size = size * scaleFactor;
3642 lineWidth = lineWidth * scaleFactor;
3643
3644 auto sl = std::make_unique< QgsLinePatternFillSymbolLayer >();
3645 sl->setOutputUnit( sldUnitSize );
3646 sl->setColor( lineColor );
3647 sl->setLineWidth( lineWidth );
3648 sl->setLineAngle( angle );
3649 sl->setOffset( offset );
3650 sl->setDistance( size );
3651
3652 // try to get the stroke
3653 QDomElement strokeElem = element.firstChildElement( u"Stroke"_s );
3654 if ( !strokeElem.isNull() )
3655 {
3656 std::unique_ptr< QgsSymbolLayer > l = QgsSymbolLayerUtils::createLineLayerFromSld( strokeElem );
3657 if ( l )
3658 {
3659 QgsSymbolLayerList layers;
3660 layers.append( l.release() );
3661 sl->setSubSymbol( new QgsLineSymbol( layers ) );
3662 }
3663 }
3664
3665 return sl;
3666}
3667
3668
3670
3673{
3674 mMarkerSymbol = std::make_unique<QgsMarkerSymbol>();
3675 QgsImageFillSymbolLayer::setSubSymbol( nullptr ); //no stroke
3676}
3677
3679
3681{
3683 mDistanceXUnit = unit;
3684 mDistanceYUnit = unit;
3685 // don't change "percentage" units -- since they adapt directly to whatever other unit is set
3687 mDisplacementXUnit = unit;
3689 mDisplacementYUnit = unit;
3691 mOffsetXUnit = unit;
3693 mOffsetYUnit = unit;
3695 mRandomDeviationXUnit = unit;
3697 mRandomDeviationYUnit = unit;
3698
3699 if ( mMarkerSymbol )
3700 {
3701 mMarkerSymbol->setOutputUnit( unit );
3702 }
3703}
3704
3721
3741
3754
3770
3771std::unique_ptr<QgsSymbolLayer> QgsPointPatternFillSymbolLayer::create( const QVariantMap &properties )
3772{
3773 auto layer = std::make_unique< QgsPointPatternFillSymbolLayer >();
3774 if ( properties.contains( u"distance_x"_s ) )
3775 {
3776 layer->setDistanceX( properties[u"distance_x"_s].toDouble() );
3777 }
3778 if ( properties.contains( u"distance_y"_s ) )
3779 {
3780 layer->setDistanceY( properties[u"distance_y"_s].toDouble() );
3781 }
3782 if ( properties.contains( u"displacement_x"_s ) )
3783 {
3784 layer->setDisplacementX( properties[u"displacement_x"_s].toDouble() );
3785 }
3786 if ( properties.contains( u"displacement_y"_s ) )
3787 {
3788 layer->setDisplacementY( properties[u"displacement_y"_s].toDouble() );
3789 }
3790 if ( properties.contains( u"offset_x"_s ) )
3791 {
3792 layer->setOffsetX( properties[u"offset_x"_s].toDouble() );
3793 }
3794 if ( properties.contains( u"offset_y"_s ) )
3795 {
3796 layer->setOffsetY( properties[u"offset_y"_s].toDouble() );
3797 }
3798
3799 if ( properties.contains( u"distance_x_unit"_s ) )
3800 {
3801 layer->setDistanceXUnit( QgsUnitTypes::decodeRenderUnit( properties[u"distance_x_unit"_s].toString() ) );
3802 }
3803 if ( properties.contains( u"distance_x_map_unit_scale"_s ) )
3804 {
3805 layer->setDistanceXMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( properties[u"distance_x_map_unit_scale"_s].toString() ) );
3806 }
3807 if ( properties.contains( u"distance_y_unit"_s ) )
3808 {
3809 layer->setDistanceYUnit( QgsUnitTypes::decodeRenderUnit( properties[u"distance_y_unit"_s].toString() ) );
3810 }
3811 if ( properties.contains( u"distance_y_map_unit_scale"_s ) )
3812 {
3813 layer->setDistanceYMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( properties[u"distance_y_map_unit_scale"_s].toString() ) );
3814 }
3815 if ( properties.contains( u"displacement_x_unit"_s ) )
3816 {
3817 layer->setDisplacementXUnit( QgsUnitTypes::decodeRenderUnit( properties[u"displacement_x_unit"_s].toString() ) );
3818 }
3819 if ( properties.contains( u"displacement_x_map_unit_scale"_s ) )
3820 {
3821 layer->setDisplacementXMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( properties[u"displacement_x_map_unit_scale"_s].toString() ) );
3822 }
3823 if ( properties.contains( u"displacement_y_unit"_s ) )
3824 {
3825 layer->setDisplacementYUnit( QgsUnitTypes::decodeRenderUnit( properties[u"displacement_y_unit"_s].toString() ) );
3826 }
3827 if ( properties.contains( u"displacement_y_map_unit_scale"_s ) )
3828 {
3829 layer->setDisplacementYMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( properties[u"displacement_y_map_unit_scale"_s].toString() ) );
3830 }
3831 if ( properties.contains( u"offset_x_unit"_s ) )
3832 {
3833 layer->setOffsetXUnit( QgsUnitTypes::decodeRenderUnit( properties[u"offset_x_unit"_s].toString() ) );
3834 }
3835 if ( properties.contains( u"offset_x_map_unit_scale"_s ) )
3836 {
3837 layer->setOffsetXMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( properties[u"offset_x_map_unit_scale"_s].toString() ) );
3838 }
3839 if ( properties.contains( u"offset_y_unit"_s ) )
3840 {
3841 layer->setOffsetYUnit( QgsUnitTypes::decodeRenderUnit( properties[u"offset_y_unit"_s].toString() ) );
3842 }
3843 if ( properties.contains( u"offset_y_map_unit_scale"_s ) )
3844 {
3845 layer->setOffsetYMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( properties[u"offset_y_map_unit_scale"_s].toString() ) );
3846 }
3847
3848 if ( properties.contains( u"random_deviation_x"_s ) )
3849 {
3850 layer->setMaximumRandomDeviationX( properties[u"random_deviation_x"_s].toDouble() );
3851 }
3852 if ( properties.contains( u"random_deviation_y"_s ) )
3853 {
3854 layer->setMaximumRandomDeviationY( properties[u"random_deviation_y"_s].toDouble() );
3855 }
3856 if ( properties.contains( u"random_deviation_x_unit"_s ) )
3857 {
3858 layer->setRandomDeviationXUnit( QgsUnitTypes::decodeRenderUnit( properties[u"random_deviation_x_unit"_s].toString() ) );
3859 }
3860 if ( properties.contains( u"random_deviation_x_map_unit_scale"_s ) )
3861 {
3862 layer->setRandomDeviationXMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( properties[u"random_deviation_x_map_unit_scale"_s].toString() ) );
3863 }
3864 if ( properties.contains( u"random_deviation_y_unit"_s ) )
3865 {
3866 layer->setRandomDeviationYUnit( QgsUnitTypes::decodeRenderUnit( properties[u"random_deviation_y_unit"_s].toString() ) );
3867 }
3868 if ( properties.contains( u"random_deviation_y_map_unit_scale"_s ) )
3869 {
3870 layer->setRandomDeviationYMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( properties[u"random_deviation_y_map_unit_scale"_s].toString() ) );
3871 }
3872 unsigned long seed = 0;
3873 if ( properties.contains( u"seed"_s ) )
3874 seed = properties.value( u"seed"_s ).toUInt();
3875 else
3876 {
3877 // if we a creating a new point pattern fill from scratch, we default to a random seed
3878 // because seed based fills are just nicer for users vs seeing points jump around with every map refresh
3879 std::random_device rd;
3880 std::mt19937 mt( static_cast< int >( rd() ) );
3881 std::uniform_int_distribution<> uniformDist( 1, 999999999 );
3882 seed = uniformDist( mt );
3883 }
3884 layer->setSeed( seed );
3885
3886 if ( properties.contains( u"outline_width_unit"_s ) )
3887 {
3888 layer->setStrokeWidthUnit( QgsUnitTypes::decodeRenderUnit( properties[u"outline_width_unit"_s].toString() ) );
3889 }
3890 if ( properties.contains( u"outline_width_map_unit_scale"_s ) )
3891 {
3892 layer->setStrokeWidthMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( properties[u"outline_width_map_unit_scale"_s].toString() ) );
3893 }
3894 if ( properties.contains( u"clip_mode"_s ) )
3895 {
3896 layer->setClipMode( QgsSymbolLayerUtils::decodeMarkerClipMode( properties.value( u"clip_mode"_s ).toString() ) );
3897 }
3898 if ( properties.contains( u"coordinate_reference"_s ) )
3899 {
3900 layer->setCoordinateReference( QgsSymbolLayerUtils::decodeCoordinateReference( properties[u"coordinate_reference"_s].toString() ) );
3901 }
3902
3903 if ( properties.contains( u"angle"_s ) )
3904 {
3905 layer->setAngle( properties[u"angle"_s].toDouble() );
3906 }
3907
3909
3910 return layer;
3911}
3912
3914{
3915 return u"PointPatternFill"_s;
3916}
3917
3918bool QgsPointPatternFillSymbolLayer::applyPattern(
3919 const QgsSymbolRenderContext &context, QBrush &brush, double distanceX, double distanceY, double displacementX, double displacementY, double offsetX, double offsetY
3920)
3921{
3922 //render 3 rows and columns in one go to easily incorporate displacement
3923 const QgsRenderContext &ctx = context.renderContext();
3926
3927 double widthOffset = std::fmod( mOffsetXUnit == Qgis::RenderUnit::Percentage ? ( width * offsetX / 200 ) : ctx.convertToPainterUnits( offsetX, mOffsetXUnit, mOffsetXMapUnitScale ), width );
3928 double heightOffset = std::fmod( mOffsetYUnit == Qgis::RenderUnit::Percentage ? ( height * offsetY / 200 ) : ctx.convertToPainterUnits( offsetY, mOffsetYUnit, mOffsetYMapUnitScale ), height );
3929
3930 if ( width > 2000 || height > 2000 ) //protect symbol layer from eating too much memory
3931 {
3932 brush.setTextureImage( QImage() );
3933 return false;
3934 }
3935
3936 QImage patternImage( width, height, QImage::Format_ARGB32 );
3937 patternImage.fill( 0 );
3938 if ( patternImage.isNull() )
3939 {
3940 brush.setTextureImage( QImage() );
3941 return false;
3942 }
3943 if ( mMarkerSymbol )
3944 {
3945 QPainter p( &patternImage );
3946
3947 //marker rendering needs context for drawing on patternImage
3948 QgsRenderContext pointRenderContext;
3949 pointRenderContext.setRendererScale( context.renderContext().rendererScale() );
3950 pointRenderContext.setPainter( &p );
3951 pointRenderContext.setScaleFactor( context.renderContext().scaleFactor() );
3952
3954 QgsMapToPixel mtp( context.renderContext().mapToPixel().mapUnitsPerPixel() );
3955 pointRenderContext.setMapToPixel( mtp );
3956 pointRenderContext.setExpressionContext( context.renderContext().expressionContext() );
3958
3960 mMarkerSymbol->startRender( pointRenderContext, context.fields() );
3961
3962 //render points on distance grid
3963 for ( double currentX = -width; currentX <= width * 2.0; currentX += width )
3964 {
3965 for ( double currentY = -height; currentY <= height * 2.0; currentY += height )
3966 {
3967 mMarkerSymbol->renderPoint( QPointF( currentX + widthOffset, currentY + heightOffset ), context.feature(), pointRenderContext );
3968 }
3969 }
3970
3971 //render displaced points
3972 double displacementPixelX = mDisplacementXUnit == Qgis::RenderUnit::Percentage ? ( width * displacementX / 200 )
3973 : ctx.convertToPainterUnits( displacementX, mDisplacementXUnit, mDisplacementXMapUnitScale );
3974 double displacementPixelY = mDisplacementYUnit == Qgis::RenderUnit::Percentage ? ( height * displacementY / 200 )
3976 for ( double currentX = -width; currentX <= width * 2.0; currentX += width )
3977 {
3978 for ( double currentY = -height / 2.0; currentY <= height * 2.0; currentY += height )
3979 {
3980 mMarkerSymbol->renderPoint( QPointF( currentX + widthOffset + displacementPixelX, currentY + heightOffset ), context.feature(), pointRenderContext );
3981 }
3982 }
3983
3984 for ( double currentX = -width / 2.0; currentX <= width * 2.0; currentX += width )
3985 {
3986 for ( double currentY = -height; currentY <= height * 2.0; currentY += height / 2.0 )
3987 {
3988 mMarkerSymbol->renderPoint( QPointF( currentX + widthOffset + ( std::fmod( currentY, height ) != 0 ? displacementPixelX : 0 ), currentY + heightOffset - displacementPixelY ), context.feature(), pointRenderContext );
3989 }
3990 }
3991
3992 mMarkerSymbol->stopRender( pointRenderContext );
3993 }
3994
3995 if ( !qgsDoubleNear( context.opacity(), 1.0 ) )
3996 {
3997 QImage transparentImage = patternImage.copy();
3998 QgsSymbolLayerUtils::multiplyImageOpacity( &transparentImage, context.opacity() );
3999 brush.setTextureImage( transparentImage );
4000 }
4001 else
4002 {
4003 brush.setTextureImage( patternImage );
4004 }
4005 QTransform brushTransform;
4006 brush.setTransform( brushTransform );
4007
4008 return true;
4009}
4010
4012{
4013 // if we are using a vector based output, we need to render points as vectors
4014 // (OR if the marker has data defined symbology, in which case we need to evaluate this point-by-point)
4015 mRenderUsingMarkers = context.forceVectorRendering()
4016 || ( mMarkerSymbol && mMarkerSymbol->hasDataDefinedProperties() )
4020 || mClipMode != Qgis::MarkerClipMode::Shape
4023 || !qgsDoubleNear( mAngle, 0 )
4025
4026 if ( !mRenderUsingMarkers )
4027 {
4028 // optimised render for screen only, use image based brush
4029 // (fallback to line rendering when pattern image will result in too large a memory footprint)
4030 mRenderUsingMarkers = !applyPattern( context, mBrush, mDistanceX, mDistanceY, mDisplacementX, mDisplacementY, mOffsetX, mOffsetY );
4031 }
4032
4033 if ( mRenderUsingMarkers && mMarkerSymbol )
4034 {
4036 mMarkerSymbol->startRender( context.renderContext(), context.fields() );
4038 }
4039}
4040
4042{
4044 {
4045 mMarkerSymbol->stopRender( context.renderContext() );
4047 }
4048}
4049
4051{
4052 installMasks( context, true );
4053
4054 // The base class version passes this on to the subsymbol, but we deliberately don't do that here.
4055 // Otherwise generators used in the subsymbol will only render a single point per feature (they
4056 // have logic to only render once per paired call to startFeatureRender/stopFeatureRender).
4057}
4058
4060{
4061 removeMasks( context, true );
4062
4063 // The base class version passes this on to the subsymbol, but we deliberately don't do that here.
4064 // Otherwise generators used in the subsymbol will only render a single point per feature (they
4065 // have logic to only render once per paired call to startFeatureRender/stopFeatureRender).
4066}
4067
4068void QgsPointPatternFillSymbolLayer::renderPolygon( const QPolygonF &points, const QVector<QPolygonF> *rings, QgsSymbolRenderContext &context )
4069{
4070 const bool useSelectedColor = shouldRenderUsingSelectionColor( context );
4071 if ( !useSelectedColor && !mRenderUsingMarkers )
4072 {
4073 // use image based brush for speed
4074 QgsImageFillSymbolLayer::renderPolygon( points, rings, context );
4075 return;
4076 }
4077
4079 {
4081 mMarkerSymbol->startRender( context.renderContext(), context.fields() );
4083 }
4084
4085 // vector based output - so draw dot by dot!
4086 QPainter *p = context.renderContext().painter();
4087 if ( !p )
4088 {
4089 return;
4090 }
4091
4092 double angle = mAngle;
4094 {
4097 }
4098
4099 double distanceX = mDistanceX;
4101 {
4104 }
4106
4107 double distanceY = mDistanceY;
4109 {
4112 }
4114
4115 double offsetX = mOffsetX;
4117 {
4120 }
4121 const double widthOffset
4123
4124 double offsetY = mOffsetY;
4126 {
4129 }
4130 const double heightOffset
4132
4135 {
4138 }
4139 const double displacementPixelX = mDisplacementXUnit == Qgis::RenderUnit::Percentage ? ( displacementX * width / 100 )
4141
4144 {
4147 }
4148 const double displacementPixelY = mDisplacementYUnit == Qgis::RenderUnit::Percentage ? ( displacementY * height / 100 )
4150
4151 p->setPen( QPen( Qt::NoPen ) );
4152
4153 // if invalid parameters, skip out
4154 if ( qgsDoubleNear( width, 0 ) || qgsDoubleNear( height, 0 ) || width < 0 || height < 0 )
4155 return;
4156
4157 // Clip width and heights steps to a reasonable distance to avoid app freezes
4158 width = std::max( ( context.renderContext().flags() & Qgis::RenderContextFlag::RenderLayerTree ) ? 0.1 : 0.025, width );
4159 height = std::max( ( context.renderContext().flags() & Qgis::RenderContextFlag::RenderLayerTree ) ? 0.1 : 0.025, height );
4160
4161 QgsScopedQPainterState painterState( p );
4162
4163 Qgis::MarkerClipMode clipMode = mClipMode;
4165 {
4167 bool ok = false;
4168 const QString valueString = mDataDefinedProperties.valueAsString( QgsSymbolLayer::Property::MarkerClipping, context.renderContext().expressionContext(), QString(), &ok );
4169 if ( ok )
4170 {
4171 Qgis::MarkerClipMode decodedMode = QgsSymbolLayerUtils::decodeMarkerClipMode( valueString, &ok );
4172 if ( ok )
4173 clipMode = decodedMode;
4174 }
4175 }
4176
4177 std::unique_ptr< QgsPolygon > shapePolygon;
4178 std::unique_ptr< QgsGeometryEngine > shapeEngine;
4179 switch ( clipMode )
4180 {
4184 {
4185 shapePolygon = std::make_unique< QgsPolygon >();
4186 std::unique_ptr< QgsLineString > fromPolygon = QgsLineString::fromQPolygonF( points );
4187 shapePolygon->setExteriorRing( fromPolygon.release() );
4188 if ( rings )
4189 {
4190 for ( const QPolygonF &ring : *rings )
4191 {
4192 std::unique_ptr< QgsLineString > fromRing = QgsLineString::fromQPolygonF( ring );
4193 shapePolygon->addInteriorRing( fromRing.release() );
4194 }
4195 }
4196 shapeEngine = QgsGeometry::createGeometryEngine( shapePolygon.get() );
4197 shapeEngine->prepareGeometry();
4198 break;
4199 }
4200
4202 {
4203 QPainterPath path;
4204 path.addPolygon( points );
4205 if ( rings )
4206 {
4207 for ( const QPolygonF &ring : *rings )
4208 {
4209 path.addPolygon( ring );
4210 }
4211 }
4212 p->setClipPath( path, Qt::IntersectClip );
4213 break;
4214 }
4215 }
4216
4217 const bool applyBrushTransform = applyBrushTransformFromContext( &context );
4218 const QRectF boundingRect = points.boundingRect();
4219
4220 QTransform invertedRotateTransform;
4221 double left;
4222 double top;
4223 double right;
4224 double bottom;
4225
4226 if ( !qgsDoubleNear( angle, 0 ) )
4227 {
4228 QTransform transform;
4229 if ( applyBrushTransform )
4230 {
4231 // rotation applies around center of feature
4232 transform.translate( -boundingRect.center().x(), -boundingRect.center().y() );
4233 transform.rotate( -angle );
4234 transform.translate( boundingRect.center().x(), boundingRect.center().y() );
4235 }
4236 else
4237 {
4238 // rotation applies around top of viewport
4239 transform.rotate( -angle );
4240 }
4241
4242 const QRectF transformedBounds = transform.map( points ).boundingRect();
4243 left = transformedBounds.left() - 2 * width;
4244 top = transformedBounds.top() - 2 * height;
4245 right = transformedBounds.right() + 2 * width;
4246 bottom = transformedBounds.bottom() + 2 * height;
4247 invertedRotateTransform = transform.inverted();
4248
4249 if ( !applyBrushTransform )
4250 {
4251 left -= transformedBounds.left() - ( width * std::floor( transformedBounds.left() / width ) );
4252 top -= transformedBounds.top() - ( height * std::floor( transformedBounds.top() / height ) );
4253 }
4254 }
4255 else
4256 {
4257 left = boundingRect.left() - 2 * width;
4258 top = boundingRect.top() - 2 * height;
4259 right = boundingRect.right() + 2 * width;
4260 bottom = boundingRect.bottom() + 2 * height;
4261
4262 if ( !applyBrushTransform )
4263 {
4264 left -= boundingRect.left() - ( width * std::floor( boundingRect.left() / width ) );
4265 top -= boundingRect.top() - ( height * std::floor( boundingRect.top() / height ) );
4266 }
4267 }
4268
4269 unsigned long seed = mSeed;
4271 {
4272 context.renderContext().expressionContext().setOriginalValueVariable( static_cast< unsigned long long >( seed ) );
4274 }
4275
4276 double maxRandomDeviationX = mRandomDeviationX;
4278 {
4279 context.setOriginalValueVariable( maxRandomDeviationX );
4280 maxRandomDeviationX = mDataDefinedProperties.valueAsDouble( QgsSymbolLayer::Property::RandomOffsetX, context.renderContext().expressionContext(), maxRandomDeviationX );
4281 }
4282 const double maxRandomDeviationPixelX = mRandomDeviationXUnit == Qgis::RenderUnit::Percentage
4283 ? ( maxRandomDeviationX * width / 100 )
4285
4286 double maxRandomDeviationY = mRandomDeviationY;
4288 {
4289 context.setOriginalValueVariable( maxRandomDeviationY );
4290 maxRandomDeviationY = mDataDefinedProperties.valueAsDouble( QgsSymbolLayer::Property::RandomOffsetY, context.renderContext().expressionContext(), maxRandomDeviationY );
4291 }
4292 const double maxRandomDeviationPixelY = mRandomDeviationYUnit == Qgis::RenderUnit::Percentage
4293 ? ( maxRandomDeviationY * height / 100 )
4295
4296 std::random_device rd;
4297 std::mt19937 mt( seed == 0 ? rd() : seed );
4298 std::uniform_real_distribution<> uniformDist( 0, 1 );
4299 const bool useRandomShift = !qgsDoubleNear( maxRandomDeviationPixelX, 0 ) || !qgsDoubleNear( maxRandomDeviationPixelY, 0 );
4300
4302 QgsExpressionContextScopePopper scopePopper( context.renderContext().expressionContext(), scope );
4303 int pointNum = 0;
4304 const bool needsExpressionContext = mMarkerSymbol->hasDataDefinedProperties();
4305
4306 const bool prevIsSubsymbol = context.renderContext().flags() & Qgis::RenderContextFlag::RenderingSubSymbol;
4308
4309 const double prevOpacity = mMarkerSymbol->opacity();
4310 mMarkerSymbol->setOpacity( mMarkerSymbol->opacity() * context.opacity() );
4311
4312 bool alternateColumn = false;
4313 int currentCol = -3; // because we actually render a few rows/cols outside the bounds, try to align the col/row numbers to start at 1 for the first visible row/col
4314 for ( double currentX = left; currentX <= right; currentX += width, alternateColumn = !alternateColumn )
4315 {
4316 if ( context.renderContext().renderingStopped() )
4317 break;
4318
4319 if ( needsExpressionContext )
4320 scope->addVariable( QgsExpressionContextScope::StaticVariable( u"symbol_marker_column"_s, ++currentCol, true ) );
4321
4322 bool alternateRow = false;
4323 const double columnX = currentX + widthOffset;
4324 int currentRow = -3;
4325 for ( double currentY = top; currentY <= bottom; currentY += height, alternateRow = !alternateRow )
4326 {
4327 if ( context.renderContext().renderingStopped() )
4328 break;
4329
4330 double y = currentY + heightOffset;
4331 double x = columnX;
4332 if ( alternateRow )
4333 x += displacementPixelX;
4334
4335 if ( !alternateColumn )
4336 y -= displacementPixelY;
4337
4338 if ( !qgsDoubleNear( angle, 0 ) )
4339 {
4340 double xx = x;
4341 double yy = y;
4342 invertedRotateTransform.map( xx, yy, &x, &y );
4343 }
4344
4345 if ( useRandomShift )
4346 {
4347 x += ( 2 * uniformDist( mt ) - 1 ) * maxRandomDeviationPixelX;
4348 y += ( 2 * uniformDist( mt ) - 1 ) * maxRandomDeviationPixelY;
4349 }
4350
4351 if ( needsExpressionContext )
4352 {
4354 scope->addVariable( QgsExpressionContextScope::StaticVariable( u"symbol_marker_row"_s, ++currentRow, true ) );
4355 }
4356
4357 if ( shapeEngine )
4358 {
4359 bool renderPoint = true;
4360 switch ( clipMode )
4361 {
4363 {
4364 // we test using the marker bounds here and NOT just the x,y point, as the marker symbol may have offsets or other data defined properties which affect its visual placement
4365 const QgsRectangle markerRect = QgsRectangle( mMarkerSymbol->bounds( QPointF( x, y ), context.renderContext(), context.feature() ? *context.feature() : QgsFeature() ) );
4366 QgsPoint p( markerRect.center() );
4367 renderPoint = shapeEngine->intersects( &p );
4368 break;
4369 }
4370
4373 {
4374 const QgsGeometry markerBounds = QgsGeometry::fromRect(
4375 QgsRectangle( mMarkerSymbol->bounds( QPointF( x, y ), context.renderContext(), context.feature() ? *context.feature() : QgsFeature() ) )
4376 );
4377
4379 renderPoint = shapeEngine->contains( markerBounds.constGet() );
4380 else
4381 renderPoint = shapeEngine->intersects( markerBounds.constGet() );
4382 break;
4383 }
4384
4386 break;
4387 }
4388
4389 if ( !renderPoint )
4390 continue;
4391 }
4392
4393 mMarkerSymbol->renderPoint( QPointF( x, y ), context.feature(), context.renderContext(), -1, useSelectedColor );
4394 }
4395 }
4396
4397 mMarkerSymbol->setOpacity( prevOpacity );
4398
4400}
4401
4403{
4404 QVariantMap map = QgsImageFillSymbolLayer::properties();
4405 map.insert( u"distance_x"_s, QString::number( mDistanceX ) );
4406 map.insert( u"distance_y"_s, QString::number( mDistanceY ) );
4407 map.insert( u"displacement_x"_s, QString::number( mDisplacementX ) );
4408 map.insert( u"displacement_y"_s, QString::number( mDisplacementY ) );
4409 map.insert( u"offset_x"_s, QString::number( mOffsetX ) );
4410 map.insert( u"offset_y"_s, QString::number( mOffsetY ) );
4411 map.insert( u"distance_x_unit"_s, QgsUnitTypes::encodeUnit( mDistanceXUnit ) );
4412 map.insert( u"distance_y_unit"_s, QgsUnitTypes::encodeUnit( mDistanceYUnit ) );
4413 map.insert( u"displacement_x_unit"_s, QgsUnitTypes::encodeUnit( mDisplacementXUnit ) );
4414 map.insert( u"displacement_y_unit"_s, QgsUnitTypes::encodeUnit( mDisplacementYUnit ) );
4415 map.insert( u"offset_x_unit"_s, QgsUnitTypes::encodeUnit( mOffsetXUnit ) );
4416 map.insert( u"offset_y_unit"_s, QgsUnitTypes::encodeUnit( mOffsetYUnit ) );
4417 map.insert( u"distance_x_map_unit_scale"_s, QgsSymbolLayerUtils::encodeMapUnitScale( mDistanceXMapUnitScale ) );
4418 map.insert( u"distance_y_map_unit_scale"_s, QgsSymbolLayerUtils::encodeMapUnitScale( mDistanceYMapUnitScale ) );
4419 map.insert( u"displacement_x_map_unit_scale"_s, QgsSymbolLayerUtils::encodeMapUnitScale( mDisplacementXMapUnitScale ) );
4420 map.insert( u"displacement_y_map_unit_scale"_s, QgsSymbolLayerUtils::encodeMapUnitScale( mDisplacementYMapUnitScale ) );
4421 map.insert( u"offset_x_map_unit_scale"_s, QgsSymbolLayerUtils::encodeMapUnitScale( mOffsetXMapUnitScale ) );
4422 map.insert( u"offset_y_map_unit_scale"_s, QgsSymbolLayerUtils::encodeMapUnitScale( mOffsetYMapUnitScale ) );
4423 map.insert( u"outline_width_unit"_s, QgsUnitTypes::encodeUnit( mStrokeWidthUnit ) );
4424 map.insert( u"outline_width_map_unit_scale"_s, QgsSymbolLayerUtils::encodeMapUnitScale( mStrokeWidthMapUnitScale ) );
4425 map.insert( u"clip_mode"_s, QgsSymbolLayerUtils::encodeMarkerClipMode( mClipMode ) );
4426 map.insert( u"random_deviation_x"_s, QString::number( mRandomDeviationX ) );
4427 map.insert( u"random_deviation_y"_s, QString::number( mRandomDeviationY ) );
4428 map.insert( u"random_deviation_x_unit"_s, QgsUnitTypes::encodeUnit( mRandomDeviationXUnit ) );
4429 map.insert( u"random_deviation_y_unit"_s, QgsUnitTypes::encodeUnit( mRandomDeviationYUnit ) );
4430 map.insert( u"random_deviation_x_map_unit_scale"_s, QgsSymbolLayerUtils::encodeMapUnitScale( mRandomDeviationXMapUnitScale ) );
4431 map.insert( u"random_deviation_y_map_unit_scale"_s, QgsSymbolLayerUtils::encodeMapUnitScale( mRandomDeviationYMapUnitScale ) );
4432 map.insert( u"seed"_s, QString::number( mSeed ) );
4433 map.insert( u"angle"_s, mAngle );
4434 return map;
4435}
4436
4438{
4439 auto clonedLayer = qgis::unique_ptr_static_cast<QgsPointPatternFillSymbolLayer>( QgsPointPatternFillSymbolLayer::create( properties() ) );
4440 if ( mMarkerSymbol )
4441 {
4442 clonedLayer->setSubSymbol( mMarkerSymbol->clone() );
4443 }
4444 clonedLayer->setClipMode( mClipMode );
4445 copyCommonProperties( clonedLayer.get() );
4446 return clonedLayer.release();
4447}
4448
4449void QgsPointPatternFillSymbolLayer::toSld( QDomDocument &doc, QDomElement &element, const QVariantMap &props ) const
4450{
4451 QgsSldExportContext context;
4452 context.setExtraProperties( props );
4453 toSld( doc, element, context );
4454}
4455
4456bool QgsPointPatternFillSymbolLayer::toSld( QDomDocument &doc, QDomElement &element, QgsSldExportContext &context ) const
4457{
4458 const QVariantMap props = context.extraProperties();
4459 for ( int symbolLayerIdx = 0; symbolLayerIdx < mMarkerSymbol->symbolLayerCount(); symbolLayerIdx++ )
4460 {
4461 QDomElement symbolizerElem = doc.createElement( u"se:PolygonSymbolizer"_s );
4462 if ( !props.value( u"uom"_s, QString() ).toString().isEmpty() )
4463 symbolizerElem.setAttribute( u"uom"_s, props.value( u"uom"_s, QString() ).toString() );
4464 element.appendChild( symbolizerElem );
4465
4466 // <Geometry>
4467 QgsSymbolLayerUtils::createGeometryElement( doc, symbolizerElem, props.value( u"geom"_s, QString() ).toString(), context );
4468
4469 QDomElement fillElem = doc.createElement( u"se:Fill"_s );
4470 symbolizerElem.appendChild( fillElem );
4471
4472 QDomElement graphicFillElem = doc.createElement( u"se:GraphicFill"_s );
4473 fillElem.appendChild( graphicFillElem );
4474
4475 QgsSymbolLayer *layer = mMarkerSymbol->symbolLayer( symbolLayerIdx );
4476
4477 // Export to PNG (TODO: SVG)
4478 bool exportOk { false };
4479 if ( !context.exportFilePath().isEmpty() && context.exportOptions().testFlag( Qgis::SldExportOption::Png ) )
4480 {
4481 const QImage image { toTiledPatternImage() };
4482 if ( !image.isNull() )
4483 {
4484 QDomElement graphicElem = doc.createElement( u"se:Graphic"_s );
4485 graphicFillElem.appendChild( graphicElem );
4486 const QFileInfo info { context.exportFilePath() };
4487 QString pngPath { info.completeSuffix().isEmpty() ? context.exportFilePath() : context.exportFilePath().chopped( info.completeSuffix().length() ).append( u"png"_s ) };
4488 pngPath = QgsFileUtils::uniquePath( pngPath );
4489 image.save( pngPath );
4490 QgsSymbolLayerUtils::externalGraphicToSld( doc, graphicElem, QFileInfo( pngPath ).fileName(), u"image/png"_s, QColor(), image.height() );
4491 exportOk = true;
4492 }
4493 }
4494
4495 if ( !exportOk )
4496 {
4497 // Converts to GeoServer "graphic-margin": symbol size must be subtracted from distance and then divided by 2
4498 const double markerSize { mMarkerSymbol->size() };
4499
4500 // store distanceX, distanceY, displacementX, displacementY in a <VendorOption>
4503 // From: https://docs.geoserver.org/stable/en/user/styling/sld/extensions/margins.html
4504 // top-bottom,right-left (two values, top and bottom sharing the same value)
4505 const QString marginSpec = QString( "%1 %2" ).arg( qgsDoubleToString( ( dy - markerSize ) / 2, 2 ), qgsDoubleToString( ( dx - markerSize ) / 2, 2 ) );
4506
4507 QDomElement graphicMarginElem = QgsSymbolLayerUtils::createVendorOptionElement( doc, u"graphic-margin"_s, marginSpec );
4508 symbolizerElem.appendChild( graphicMarginElem );
4509
4510 if ( QgsMarkerSymbolLayer *markerLayer = dynamic_cast<QgsMarkerSymbolLayer *>( layer ) )
4511 {
4512 markerLayer->writeSldMarker( doc, graphicFillElem, context );
4513 }
4514 else if ( layer )
4515 {
4516 QgsDebugError( u"QgsMarkerSymbolLayer expected, %1 found. Skip it."_s.arg( layer->layerType() ) );
4517 }
4518 else
4519 {
4520 QgsDebugError( u"Missing point pattern symbol layer. Skip it."_s );
4521 }
4522 }
4523 }
4524 return true;
4525}
4526
4528{
4529 double angleRads { qDegreesToRadians( mAngle ) };
4530
4531 int distanceXPx { static_cast<int>( QgsSymbolLayerUtils::rescaleUom( mDistanceX, mDistanceXUnit, {} ) ) };
4532 int distanceYPx { static_cast<int>( QgsSymbolLayerUtils::rescaleUom( mDistanceY, mDistanceYUnit, {} ) ) };
4533
4534 const int displacementXPx { static_cast<int>( QgsSymbolLayerUtils::rescaleUom( mDisplacementX, mDisplacementXUnit, {} ) ) };
4535 const int displacementYPx { static_cast<int>( QgsSymbolLayerUtils::rescaleUom( mDisplacementY, mDisplacementYUnit, {} ) ) };
4536
4537 // Consider displacement, double the distance.
4538 if ( displacementXPx != 0 )
4539 {
4540 distanceXPx *= 2;
4541 }
4542
4543 if ( displacementYPx != 0 )
4544 {
4545 distanceYPx *= 2;
4546 }
4547
4548 const QSize size { QgsSymbolLayerUtils::tileSize( distanceXPx, distanceYPx, angleRads ) };
4549
4550 QPixmap pixmap( size );
4551 pixmap.fill( Qt::transparent );
4552 QPainter painter;
4553 painter.begin( &pixmap );
4554 painter.setRenderHint( QPainter::Antialiasing );
4555 QgsRenderContext renderContext = QgsRenderContext::fromQPainter( &painter );
4560 QgsSymbolRenderContext symbolContext( renderContext, Qgis::RenderUnit::Pixels, 1.0, false, Qgis::SymbolRenderHints() );
4561
4562 std::unique_ptr< QgsPointPatternFillSymbolLayer > layerClone( clone() );
4563
4564 layerClone->setAngle( qRadiansToDegrees( angleRads ) );
4565
4566 // No way we can export a random pattern, disable it.
4567 layerClone->setMaximumRandomDeviationX( 0 );
4568 layerClone->setMaximumRandomDeviationY( 0 );
4569
4570 layerClone->drawPreviewIcon( symbolContext, pixmap.size() );
4571 painter.end();
4572 return pixmap.toImage();
4573}
4574
4575std::unique_ptr<QgsSymbolLayer> QgsPointPatternFillSymbolLayer::createFromSld( QDomElement &element )
4576{
4577 // input element is PolygonSymbolizer
4578
4579 QDomElement fillElem = element.firstChildElement( u"Fill"_s );
4580 if ( fillElem.isNull() )
4581 return nullptr;
4582
4583 QDomElement graphicFillElem = fillElem.firstChildElement( u"GraphicFill"_s );
4584 if ( graphicFillElem.isNull() )
4585 return nullptr;
4586
4587 QDomElement graphicElem = graphicFillElem.firstChildElement( u"Graphic"_s );
4588 if ( graphicElem.isNull() )
4589 return nullptr;
4590
4591 std::unique_ptr< QgsSymbolLayer > simpleMarkerSl = QgsSymbolLayerUtils::createMarkerLayerFromSld( graphicFillElem );
4592 if ( !simpleMarkerSl )
4593 return nullptr;
4594
4595 QgsSymbolLayerList layers;
4596 layers.append( simpleMarkerSl.release() );
4597
4598 auto marker = std::make_unique< QgsMarkerSymbol >( layers );
4599
4600 // Converts from GeoServer "graphic-margin": symbol size must be added and margin doubled
4601 const double markerSize { marker->size() };
4602
4603 auto pointPatternFillSl = std::make_unique< QgsPointPatternFillSymbolLayer >();
4604 pointPatternFillSl->setSubSymbol( marker.release() );
4605 // This may not be correct in all cases, TODO: check "uom"
4606 pointPatternFillSl->setDistanceXUnit( Qgis::RenderUnit::Pixels );
4607 pointPatternFillSl->setDistanceYUnit( Qgis::RenderUnit::Pixels );
4608
4609 auto distanceParser = [&]( const QStringList &values ) {
4610 switch ( values.count() )
4611 {
4612 case 1: // top-right-bottom-left (single value for all four margins)
4613 {
4614 bool ok;
4615 const double v { values.at( 0 ).toDouble( &ok ) };
4616 if ( ok )
4617 {
4618 pointPatternFillSl->setDistanceX( v * 2 + markerSize );
4619 pointPatternFillSl->setDistanceY( v * 2 + markerSize );
4620 }
4621 break;
4622 }
4623 case 2: // top-bottom,right-left (two values, top and bottom sharing the same value)
4624 {
4625 bool ok;
4626 const double vX { values.at( 1 ).toDouble( &ok ) };
4627 if ( ok )
4628 {
4629 pointPatternFillSl->setDistanceX( vX * 2 + markerSize );
4630 }
4631 const double vY { values.at( 0 ).toDouble( &ok ) };
4632 if ( ok )
4633 {
4634 pointPatternFillSl->setDistanceY( vY * 2 + markerSize );
4635 }
4636 break;
4637 }
4638 case 3: // top,right-left,bottom (three values, with right and left sharing the same value)
4639 {
4640 bool ok;
4641 const double vX { values.at( 1 ).toDouble( &ok ) };
4642 if ( ok )
4643 {
4644 pointPatternFillSl->setDistanceX( vX * 2 + markerSize );
4645 }
4646 const double vYt { values.at( 0 ).toDouble( &ok ) };
4647 if ( ok )
4648 {
4649 const double vYb { values.at( 2 ).toDouble( &ok ) };
4650 if ( ok )
4651 {
4652 pointPatternFillSl->setDistanceY( ( vYt + vYb ) + markerSize );
4653 }
4654 }
4655 break;
4656 }
4657 case 4: // top,right,bottom,left (one explicit value per margin)
4658 {
4659 bool ok;
4660 const double vYt { values.at( 0 ).toDouble( &ok ) };
4661 if ( ok )
4662 {
4663 const double vYb { values.at( 2 ).toDouble( &ok ) };
4664 if ( ok )
4665 {
4666 pointPatternFillSl->setDistanceY( ( vYt + vYb ) + markerSize );
4667 }
4668 }
4669 const double vXr { values.at( 1 ).toDouble( &ok ) };
4670 if ( ok )
4671 {
4672 const double vXl { values.at( 3 ).toDouble( &ok ) };
4673 if ( ok )
4674 {
4675 pointPatternFillSl->setDistanceX( ( vXr + vXl ) + markerSize );
4676 }
4677 }
4678 break;
4679 }
4680 default:
4681 break;
4682 }
4683 };
4684
4685 // Set distance X and Y from vendor options, or from Size if no vendor options are set
4686 bool distanceFromVendorOption { false };
4687 QgsStringMap vendorOptions = QgsSymbolLayerUtils::getVendorOptionList( element );
4688 for ( QgsStringMap::iterator it = vendorOptions.begin(); it != vendorOptions.end(); ++it )
4689 {
4690 // Legacy
4691 if ( it.key() == "distance"_L1 )
4692 {
4693 distanceParser( it.value().split( ',' ) );
4694 distanceFromVendorOption = true;
4695 }
4696 // GeoServer
4697 else if ( it.key() == "graphic-margin"_L1 )
4698 {
4699 distanceParser( it.value().split( ' ' ) );
4700 distanceFromVendorOption = true;
4701 }
4702 }
4703
4704 // Get distances from size
4705 if ( !distanceFromVendorOption && !graphicFillElem.elementsByTagName( u"Size"_s ).isEmpty() )
4706 {
4707 const QDomElement sizeElement { graphicFillElem.elementsByTagName( u"Size"_s ).at( 0 ).toElement() };
4708 bool ok;
4709 const double size { sizeElement.text().toDouble( &ok ) };
4710 if ( ok )
4711 {
4712 pointPatternFillSl->setDistanceX( size );
4713 pointPatternFillSl->setDistanceY( size );
4714 }
4715 }
4716
4717 return pointPatternFillSl;
4718}
4719
4721{
4722 if ( !symbol )
4723 {
4724 return false;
4725 }
4726
4727 if ( symbol->type() == Qgis::SymbolType::Marker )
4728 {
4729 QgsMarkerSymbol *markerSymbol = static_cast<QgsMarkerSymbol *>( symbol );
4730 mMarkerSymbol.reset( markerSymbol );
4731 }
4732 return true;
4733}
4734
4739
4741{
4748 && ( !mMarkerSymbol || !mMarkerSymbol->hasDataDefinedProperties() ) )
4749 {
4750 return;
4751 }
4752
4753 double distanceX = mDistanceX;
4755 {
4758 }
4759 double distanceY = mDistanceY;
4761 {
4764 }
4767 {
4770 }
4773 {
4776 }
4777 double offsetX = mOffsetX;
4779 {
4782 }
4783 double offsetY = mOffsetY;
4785 {
4788 }
4789 applyPattern( context, mBrush, distanceX, distanceY, displacementX, displacementY, offsetX, offsetY );
4790}
4791
4793{
4794 return 0;
4795}
4796
4798{
4799 QSet<QString> attributes = QgsImageFillSymbolLayer::usedAttributes( context );
4800
4801 if ( mMarkerSymbol )
4802 attributes.unite( mMarkerSymbol->usedAttributes( context ) );
4803
4804 return attributes;
4805}
4806
4808{
4810 return true;
4811 if ( mMarkerSymbol && mMarkerSymbol->hasDataDefinedProperties() )
4812 return true;
4813 return false;
4814}
4815
4817{
4818 mColor = c;
4819 if ( mMarkerSymbol )
4820 mMarkerSymbol->setColor( c );
4821}
4822
4824{
4825 return mMarkerSymbol ? mMarkerSymbol->color() : mColor;
4826}
4827
4829
4830
4835
4837
4838std::unique_ptr<QgsSymbolLayer> QgsCentroidFillSymbolLayer::create( const QVariantMap &properties )
4839{
4840 auto sl = std::make_unique< QgsCentroidFillSymbolLayer >();
4841
4842 if ( properties.contains( u"point_on_surface"_s ) )
4843 sl->setPointOnSurface( properties[u"point_on_surface"_s].toInt() != 0 );
4844 if ( properties.contains( u"point_on_all_parts"_s ) )
4845 sl->setPointOnAllParts( properties[u"point_on_all_parts"_s].toInt() != 0 );
4846 if ( properties.contains( u"clip_points"_s ) )
4847 sl->setClipPoints( properties[u"clip_points"_s].toInt() != 0 );
4848 if ( properties.contains( u"clip_on_current_part_only"_s ) )
4849 sl->setClipOnCurrentPartOnly( properties[u"clip_on_current_part_only"_s].toInt() != 0 );
4850
4851 sl->restoreOldDataDefinedProperties( properties );
4852
4853 return sl;
4854}
4855
4857{
4858 return u"CentroidFill"_s;
4859}
4860
4862{
4863 mMarker->setColor( color );
4864 mColor = color;
4865}
4866
4868{
4869 return mMarker ? mMarker->color() : mColor;
4870}
4871
4873{
4874 mMarker->setRenderHints( mMarker->renderHints() | Qgis::SymbolRenderHint::IsSymbolLayerSubSymbol );
4875 mMarker->startRender( context.renderContext(), context.fields() );
4876}
4877
4879{
4880 mMarker->stopRender( context.renderContext() );
4881}
4882
4883void QgsCentroidFillSymbolLayer::renderPolygon( const QPolygonF &points, const QVector<QPolygonF> *rings, QgsSymbolRenderContext &context )
4884{
4885 Part part;
4886 part.exterior = points;
4887 if ( rings )
4888 part.rings = *rings;
4889
4890 if ( mRenderingFeature )
4891 {
4892 // in the middle of rendering a possibly multi-part feature, so we collect all the parts and defer the actual rendering
4893 // until after we've received the final part
4894 mFeatureSymbolOpacity = context.opacity();
4896 mCurrentParts << part;
4897 }
4898 else
4899 {
4900 // not rendering a feature, so we can just render the polygon immediately
4901 const double prevOpacity = mMarker->opacity();
4902 mMarker->setOpacity( mMarker->opacity() * context.opacity() );
4903 const bool useSelectedColor = shouldRenderUsingSelectionColor( context );
4904 render( context.renderContext(), QVector<Part>() << part, context.feature() ? *context.feature() : QgsFeature(), useSelectedColor );
4905 mMarker->setOpacity( prevOpacity );
4906 }
4907}
4908
4910{
4911 installMasks( context, true );
4912
4913 mRenderingFeature = true;
4914 mCurrentParts.clear();
4915}
4916
4918{
4919 mRenderingFeature = false;
4920
4921 const double prevOpacity = mMarker->opacity();
4922 mMarker->setOpacity( mMarker->opacity() * mFeatureSymbolOpacity );
4923
4924 render( context, mCurrentParts, feature, mUseSelectedColor );
4926 mUseSelectedColor = false;
4927 mMarker->setOpacity( prevOpacity );
4928
4929 removeMasks( context, true );
4930}
4931
4932void QgsCentroidFillSymbolLayer::render( QgsRenderContext &context, const QVector<QgsCentroidFillSymbolLayer::Part> &parts, const QgsFeature &feature, bool selected )
4933{
4936 bool clipPoints = mClipPoints;
4938
4939 // TODO add expressions support
4940
4941 QVector< QgsGeometry > geometryParts;
4942 geometryParts.reserve( parts.size() );
4943 QPainterPath globalPath;
4944
4945 int maxArea = 0;
4946 int maxAreaPartIdx = 0;
4947
4948 for ( int i = 0; i < parts.size(); i++ )
4949 {
4950 const Part part = parts[i];
4951 QgsGeometry geom = QgsGeometry::fromQPolygonF( part.exterior );
4952
4953 if ( !geom.isNull() && !part.rings.empty() )
4954 {
4956
4957 if ( !pointOnAllParts )
4958 {
4959 int area = poly->area();
4960
4961 if ( area > maxArea )
4962 {
4963 maxArea = area;
4964 maxAreaPartIdx = i;
4965 }
4966 }
4967 }
4968
4970 {
4971 globalPath.addPolygon( part.exterior );
4972 for ( const QPolygonF &ring : part.rings )
4973 {
4974 globalPath.addPolygon( ring );
4975 }
4976 }
4977 }
4978
4979 for ( int i = 0; i < parts.size(); i++ )
4980 {
4981 if ( !pointOnAllParts && i != maxAreaPartIdx )
4982 continue;
4983
4984 const Part part = parts[i];
4985
4986 QgsScopedQPainterState painterState( context.painter(), QgsScopedQPainterState::InitialState::NoSave );
4987 if ( clipPoints )
4988 {
4989 QPainterPath path;
4990
4992 {
4993 path.addPolygon( part.exterior );
4994 for ( const QPolygonF &ring : part.rings )
4995 {
4996 path.addPolygon( ring );
4997 }
4998 }
4999 else
5000 {
5001 path = globalPath;
5002 }
5003
5004 painterState.save();
5005 context.painter()->setClipPath( path );
5006 }
5007
5008 QPointF centroid = pointOnSurface ? QgsSymbolLayerUtils::polygonPointOnSurface( part.exterior, &part.rings ) : QgsSymbolLayerUtils::polygonCentroid( part.exterior );
5009
5010 const bool prevIsSubsymbol = context.flags() & Qgis::RenderContextFlag::RenderingSubSymbol;
5012 mMarker->renderPoint( centroid, feature.isValid() ? &feature : nullptr, context, -1, selected );
5013 context.setFlag( Qgis::RenderContextFlag::RenderingSubSymbol, prevIsSubsymbol );
5014 }
5015}
5016
5018{
5019 QVariantMap map;
5020 map[u"point_on_surface"_s] = QString::number( mPointOnSurface );
5021 map[u"point_on_all_parts"_s] = QString::number( mPointOnAllParts );
5022 map[u"clip_points"_s] = QString::number( mClipPoints );
5023 map[u"clip_on_current_part_only"_s] = QString::number( mClipOnCurrentPartOnly );
5024 return map;
5025}
5026
5028{
5029 auto x = std::make_unique< QgsCentroidFillSymbolLayer >();
5030 x->mAngle = mAngle;
5031 x->mColor = mColor;
5032 x->setSubSymbol( mMarker->clone() );
5033 x->setPointOnSurface( mPointOnSurface );
5034 x->setPointOnAllParts( mPointOnAllParts );
5035 x->setClipPoints( mClipPoints );
5036 x->setClipOnCurrentPartOnly( mClipOnCurrentPartOnly );
5037 copyCommonProperties( x.get() );
5038 return x.release();
5039}
5040
5041void QgsCentroidFillSymbolLayer::toSld( QDomDocument &doc, QDomElement &element, const QVariantMap &props ) const
5042{
5043 QgsSldExportContext context;
5044 context.setExtraProperties( props );
5045 toSld( doc, element, context );
5046}
5047
5048bool QgsCentroidFillSymbolLayer::toSld( QDomDocument &doc, QDomElement &element, QgsSldExportContext &context ) const
5049{
5050 // SLD 1.0 specs says: "if a line, polygon, or raster geometry is
5051 // used with PointSymbolizer, then the semantic is to use the centroid
5052 // of the geometry, or any similar representative point.
5053 return mMarker->toSld( doc, element, context );
5054}
5055
5056std::unique_ptr<QgsSymbolLayer> QgsCentroidFillSymbolLayer::createFromSld( QDomElement &element )
5057{
5058 std::unique_ptr< QgsSymbolLayer > l = QgsSymbolLayerUtils::createMarkerLayerFromSld( element );
5059 if ( !l )
5060 return nullptr;
5061
5062 QgsSymbolLayerList layers;
5063 layers.append( l.release() );
5064 auto marker = std::make_unique<QgsMarkerSymbol>( layers );
5065
5066 auto sl = std::make_unique< QgsCentroidFillSymbolLayer >();
5067 sl->setSubSymbol( marker.release() );
5068 sl->setPointOnAllParts( false );
5069 return sl;
5070}
5071
5072
5077
5079{
5080 if ( !symbol || symbol->type() != Qgis::SymbolType::Marker )
5081 {
5082 delete symbol;
5083 return false;
5084 }
5085
5086 mMarker.reset( static_cast<QgsMarkerSymbol *>( symbol ) );
5087 mColor = mMarker->color();
5088 return true;
5089}
5090
5092{
5093 QSet<QString> attributes = QgsFillSymbolLayer::usedAttributes( context );
5094
5095 if ( mMarker )
5096 attributes.unite( mMarker->usedAttributes( context ) );
5097
5098 return attributes;
5099}
5100
5102{
5104 return true;
5105 if ( mMarker && mMarker->hasDataDefinedProperties() )
5106 return true;
5107 return false;
5108}
5109
5114
5116{
5117 if ( mMarker )
5118 {
5119 mMarker->setOutputUnit( unit );
5120 }
5121}
5122
5124{
5125 if ( mMarker )
5126 {
5127 return mMarker->outputUnit();
5128 }
5129 return Qgis::RenderUnit::Unknown; //mOutputUnit;
5130}
5131
5133{
5134 if ( mMarker )
5135 {
5136 return mMarker->usesMapUnits();
5137 }
5138 return false;
5139}
5140
5142{
5143 if ( mMarker )
5144 {
5145 mMarker->setMapUnitScale( scale );
5146 }
5147}
5148
5150{
5151 if ( mMarker )
5152 {
5153 return mMarker->mapUnitScale();
5154 }
5155 return QgsMapUnitScale();
5156}
5157
5158
5166
5168
5169std::unique_ptr<QgsSymbolLayer> QgsRasterFillSymbolLayer::create( const QVariantMap &properties )
5170{
5172 double alpha = 1.0;
5173 QPointF offset;
5174 double angle = 0.0;
5175 double width = 0.0;
5176
5177 QString imagePath;
5178 if ( properties.contains( u"imageFile"_s ) )
5179 {
5180 imagePath = properties[u"imageFile"_s].toString();
5181 }
5182 if ( properties.contains( u"coordinate_mode"_s ) )
5183 {
5184 mode = static_cast< Qgis::SymbolCoordinateReference >( properties[u"coordinate_mode"_s].toInt() );
5185 }
5186 if ( properties.contains( u"alpha"_s ) )
5187 {
5188 alpha = properties[u"alpha"_s].toDouble();
5189 }
5190 if ( properties.contains( u"offset"_s ) )
5191 {
5192 offset = QgsSymbolLayerUtils::decodePoint( properties[u"offset"_s].toString() );
5193 }
5194 if ( properties.contains( u"angle"_s ) )
5195 {
5196 angle = properties[u"angle"_s].toDouble();
5197 }
5198 if ( properties.contains( u"width"_s ) )
5199 {
5200 width = properties[u"width"_s].toDouble();
5201 }
5202 auto symbolLayer = std::make_unique< QgsRasterFillSymbolLayer >( imagePath );
5203 symbolLayer->setCoordinateMode( mode );
5204 symbolLayer->setOpacity( alpha );
5205 symbolLayer->setOffset( offset );
5206 symbolLayer->setAngle( angle );
5207 symbolLayer->setWidth( width );
5208 if ( properties.contains( u"offset_unit"_s ) )
5209 {
5210 symbolLayer->setOffsetUnit( QgsUnitTypes::decodeRenderUnit( properties[u"offset_unit"_s].toString() ) );
5211 }
5212 if ( properties.contains( u"offset_map_unit_scale"_s ) )
5213 {
5214 symbolLayer->setOffsetMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( properties[u"offset_map_unit_scale"_s].toString() ) );
5215 }
5216 if ( properties.contains( u"width_unit"_s ) )
5217 {
5218 symbolLayer->setSizeUnit( QgsUnitTypes::decodeRenderUnit( properties[u"width_unit"_s].toString() ) );
5219 }
5220 if ( properties.contains( u"width_map_unit_scale"_s ) )
5221 {
5222 symbolLayer->setSizeMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( properties[u"width_map_unit_scale"_s].toString() ) );
5223 }
5224
5225 if ( properties.contains( u"height"_s ) )
5226 {
5227 symbolLayer->setHeight( properties[u"height"_s].toDouble() );
5228 }
5229
5230 symbolLayer->restoreOldDataDefinedProperties( properties );
5231
5232 return symbolLayer;
5233}
5234
5235std::unique_ptr<QgsSymbolLayer> QgsRasterFillSymbolLayer::createFromSld( QDomElement &element )
5236{
5237 QDomElement fillElem = element.firstChildElement( u"Fill"_s );
5238 if ( fillElem.isNull() )
5239 return nullptr;
5240
5241 QDomElement graphicFillElem = fillElem.firstChildElement( u"GraphicFill"_s );
5242 if ( graphicFillElem.isNull() )
5243 return nullptr;
5244
5245 QDomElement graphicElem = graphicFillElem.firstChildElement( u"Graphic"_s );
5246 if ( graphicElem.isNull() )
5247 return nullptr;
5248
5249 QString path, mimeType;
5250 double size;
5251 QColor fillColor;
5252
5253 if ( !QgsSymbolLayerUtils::externalGraphicFromSld( graphicElem, path, mimeType, fillColor, size ) )
5254 return nullptr;
5255
5256 // Try to correct the path, this is a wild guess but we have not access to the SLD path here.
5257 if ( !QFile::exists( path ) )
5258 {
5259 path = QgsProject::instance()->pathResolver().readPath( path ); // skip-keyword-check
5260 }
5261
5262 auto sl = std::make_unique< QgsRasterFillSymbolLayer>( path );
5263
5264 return sl;
5265}
5266
5267void QgsRasterFillSymbolLayer::resolvePaths( QVariantMap &properties, const QgsPathResolver &pathResolver, bool saving )
5268{
5269 QVariantMap::iterator it = properties.find( u"imageFile"_s );
5270 if ( it != properties.end() )
5271 {
5272 if ( saving )
5273 it.value() = pathResolver.writePath( it.value().toString() );
5274 else
5275 it.value() = pathResolver.readPath( it.value().toString() );
5276 }
5277}
5278
5280{
5281 Q_UNUSED( symbol )
5282 return true;
5283}
5284
5286{
5287 return u"RasterFill"_s;
5288}
5289
5294
5295void QgsRasterFillSymbolLayer::renderPolygon( const QPolygonF &points, const QVector<QPolygonF> *rings, QgsSymbolRenderContext &context )
5296{
5297 QPainter *p = context.renderContext().painter();
5298 if ( !p )
5299 {
5300 return;
5301 }
5302
5303 QPointF offset = mOffset;
5305 {
5307 const QVariant val = mDataDefinedProperties.value( QgsSymbolLayer::Property::Offset, context.renderContext().expressionContext(), QString() );
5308 bool ok = false;
5309 const QPointF res = QgsSymbolLayerUtils::toPoint( val, &ok );
5310 if ( ok )
5311 offset = res;
5312 }
5313 if ( !offset.isNull() )
5314 {
5315 offset.setX( context.renderContext().convertToPainterUnits( offset.x(), mOffsetUnit, mOffsetMapUnitScale ) );
5316 offset.setY( context.renderContext().convertToPainterUnits( offset.y(), mOffsetUnit, mOffsetMapUnitScale ) );
5317 p->translate( offset );
5318 }
5319 if ( mCoordinateMode == Qgis::SymbolCoordinateReference::Feature )
5320 {
5321 QRectF boundingRect = points.boundingRect();
5322 mBrush.setTransform( mBrush.transform().translate( boundingRect.left() - mBrush.transform().dx(), boundingRect.top() - mBrush.transform().dy() ) );
5323 }
5324
5325 QgsImageFillSymbolLayer::renderPolygon( points, rings, context );
5326 if ( !offset.isNull() )
5327 {
5328 p->translate( -offset );
5329 }
5330}
5331
5333{
5334 applyPattern( mBrush, mImageFilePath, mWidth, mHeight, mOpacity * context.opacity(), context );
5335}
5336
5338{
5339 Q_UNUSED( context )
5340}
5341
5343{
5344 QVariantMap map;
5345 map[u"imageFile"_s] = mImageFilePath;
5346 map[u"coordinate_mode"_s] = QString::number( static_cast< int >( mCoordinateMode ) );
5347 map[u"alpha"_s] = QString::number( mOpacity );
5348 map[u"offset"_s] = QgsSymbolLayerUtils::encodePoint( mOffset );
5349 map[u"offset_unit"_s] = QgsUnitTypes::encodeUnit( mOffsetUnit );
5350 map[u"offset_map_unit_scale"_s] = QgsSymbolLayerUtils::encodeMapUnitScale( mOffsetMapUnitScale );
5351 map[u"angle"_s] = QString::number( mAngle );
5352
5353 map[u"width"_s] = QString::number( mWidth );
5354 map[u"height"_s] = QString::number( mHeight );
5355 map[u"width_unit"_s] = QgsUnitTypes::encodeUnit( mSizeUnit );
5356 map[u"width_map_unit_scale"_s] = QgsSymbolLayerUtils::encodeMapUnitScale( mSizeMapUnitScale );
5357
5358 return map;
5359}
5360
5362{
5363 auto sl = std::make_unique< QgsRasterFillSymbolLayer >( mImageFilePath );
5364 sl->setCoordinateMode( mCoordinateMode );
5365 sl->setOpacity( mOpacity );
5366 sl->setOffset( mOffset );
5367 sl->setOffsetUnit( mOffsetUnit );
5368 sl->setOffsetMapUnitScale( mOffsetMapUnitScale );
5369 sl->setAngle( mAngle );
5370 sl->setWidth( mWidth );
5371 sl->setHeight( mHeight );
5372 sl->setSizeUnit( mSizeUnit );
5373 sl->setSizeMapUnitScale( mSizeMapUnitScale );
5374
5375 copyCommonProperties( sl.get() );
5376 return sl.release();
5377}
5378
5380{
5381 return context.convertToPainterUnits( std::max( std::fabs( mOffset.x() ), std::fabs( mOffset.y() ) ), mOffsetUnit, mOffsetMapUnitScale );
5382}
5383
5388
5390{
5391 return QColor();
5392}
5393
5395{
5397 mOffsetUnit = unit;
5398 mSizeUnit = unit;
5399}
5400
5401void QgsRasterFillSymbolLayer::setImageFilePath( const QString &imagePath )
5402{
5403 mImageFilePath = imagePath;
5404}
5405
5407{
5408 mCoordinateMode = mode;
5409}
5410
5412{
5413 mOpacity = opacity;
5414}
5415
5417{
5418 if ( !dataDefinedProperties().hasActiveProperties() )
5419 return; // shortcut
5420
5421 const bool hasWidthExpression = mDataDefinedProperties.isActive( QgsSymbolLayer::Property::Width );
5422 const bool hasHeightExpression = mDataDefinedProperties.isActive( QgsSymbolLayer::Property::Height );
5423 const bool hasFileExpression = mDataDefinedProperties.isActive( QgsSymbolLayer::Property::File );
5424 const bool hasOpacityExpression = mDataDefinedProperties.isActive( QgsSymbolLayer::Property::Opacity );
5425 const bool hasAngleExpression = mDataDefinedProperties.isActive( QgsSymbolLayer::Property::Angle );
5426
5427 if ( !hasWidthExpression && !hasHeightExpression && !hasAngleExpression && !hasOpacityExpression && !hasFileExpression )
5428 {
5429 return; //no data defined settings
5430 }
5431
5432 bool ok;
5433 if ( hasAngleExpression )
5434 {
5436 double nextAngle = mDataDefinedProperties.valueAsDouble( QgsSymbolLayer::Property::Angle, context.renderContext().expressionContext(), 0, &ok );
5437 if ( ok )
5438 mNextAngle = nextAngle;
5439 }
5440
5441 if ( !hasWidthExpression && !hasHeightExpression && !hasOpacityExpression && !hasFileExpression )
5442 {
5443 return; //nothing further to do
5444 }
5445
5446 double width = mWidth;
5447 if ( hasWidthExpression )
5448 {
5449 context.setOriginalValueVariable( mWidth );
5451 }
5452 double height = mHeight;
5453 if ( hasHeightExpression )
5454 {
5455 context.setOriginalValueVariable( mHeight );
5457 }
5458 double opacity = mOpacity;
5459 if ( hasOpacityExpression )
5460 {
5461 context.setOriginalValueVariable( mOpacity );
5463 }
5464 QString file = mImageFilePath;
5465 if ( hasFileExpression )
5466 {
5467 context.setOriginalValueVariable( mImageFilePath );
5469 }
5470 applyPattern( mBrush, file, width, height, opacity, context );
5471}
5472
5477
5478void QgsRasterFillSymbolLayer::applyPattern( QBrush &brush, const QString &imageFilePath, const double width, const double height, const double alpha, const QgsSymbolRenderContext &context )
5479{
5480 double imageWidth = 0;
5481 double imageHeight = 0;
5482
5483 // defer retrieval of original size till we actually NEED it
5484 QSize originalSize;
5485
5486 if ( width > 0 )
5487 {
5488 if ( mSizeUnit != Qgis::RenderUnit::Percentage )
5489 {
5490 imageWidth = context.renderContext().convertToPainterUnits( width, mSizeUnit, mSizeMapUnitScale );
5491 }
5492 else
5493 {
5494 // RenderPercentage Unit Type takes original image size
5496 if ( originalSize.isEmpty() )
5497 return;
5498
5499 imageWidth = ( width * originalSize.width() ) / 100.0;
5500
5501 // don't render symbols with size below one or above 10,000 pixels
5502 if ( static_cast< int >( imageWidth ) < 1 || 10000.0 < imageWidth )
5503 return;
5504 }
5505 }
5506 if ( height > 0 )
5507 {
5508 if ( mSizeUnit != Qgis::RenderUnit::Percentage )
5509 {
5510 imageHeight = context.renderContext().convertToPainterUnits( height, mSizeUnit, mSizeMapUnitScale );
5511 }
5512 else
5513 {
5514 // RenderPercentage Unit Type takes original image size
5515 if ( !originalSize.isValid() )
5517
5518 if ( originalSize.isEmpty() )
5519 return;
5520
5521 imageHeight = ( height * originalSize.height() ) / 100.0;
5522
5523 // don't render symbols with size below one or above 10,000 pixels
5524 if ( static_cast< int >( imageHeight ) < 1 || 10000.0 < imageHeight )
5525 return;
5526 }
5527 }
5528
5529 if ( width == 0 && imageHeight > 0 )
5530 {
5531 if ( !originalSize.isValid() )
5533
5534 imageWidth = imageHeight * originalSize.width() / originalSize.height();
5535 }
5536 else if ( height == 0 && imageWidth > 0 )
5537 {
5538 if ( !originalSize.isValid() )
5540
5541 imageHeight = imageWidth * originalSize.height() / originalSize.width();
5542 }
5543 if ( imageWidth == 0 || imageHeight == 0 )
5544 {
5545 if ( !originalSize.isValid() )
5547
5548 imageWidth = originalSize.width();
5549 imageHeight = originalSize.height();
5550 }
5551
5552 bool cached;
5553 QImage img
5555 ->pathAsImage( imageFilePath, QSize( std::round< int >( imageWidth ), std::round< int >( imageHeight ) ), false, alpha, cached, ( context.renderContext().flags() & Qgis::RenderContextFlag::RenderBlocking ) );
5556 if ( img.isNull() )
5557 return;
5558
5559 brush.setTextureImage( img );
5560}
5561
5562
5563//
5564// QgsRandomMarkerFillSymbolLayer
5565//
5566
5568 : mCountMethod( method )
5569 , mPointCount( pointCount )
5570 , mDensityArea( densityArea )
5571 , mSeed( seed )
5572{
5574}
5575
5577
5578std::unique_ptr<QgsSymbolLayer> QgsRandomMarkerFillSymbolLayer::create( const QVariantMap &properties )
5579{
5580 const Qgis::PointCountMethod countMethod = static_cast< Qgis::PointCountMethod >( properties.value( u"count_method"_s, u"0"_s ).toInt() );
5581 const int pointCount = properties.value( u"point_count"_s, u"10"_s ).toInt();
5582 const double densityArea = properties.value( u"density_area"_s, u"250.0"_s ).toDouble();
5583
5584 unsigned long seed = 0;
5585 if ( properties.contains( u"seed"_s ) )
5586 seed = properties.value( u"seed"_s ).toUInt();
5587 else
5588 {
5589 // if we a creating a new random marker fill from scratch, we default to a random seed
5590 // because seed based fills are just nicer for users vs seeing points jump around with every map refresh
5591 std::random_device rd;
5592 std::mt19937 mt( static_cast< int >( rd() ) );
5593 std::uniform_int_distribution<> uniformDist( 1, 999999999 );
5594 seed = uniformDist( mt );
5595 }
5596
5597 auto sl = std::make_unique< QgsRandomMarkerFillSymbolLayer >( pointCount, countMethod, densityArea, seed );
5598
5599 if ( properties.contains( u"density_area_unit"_s ) )
5600 sl->setDensityAreaUnit( QgsUnitTypes::decodeRenderUnit( properties[u"density_area_unit"_s].toString() ) );
5601 if ( properties.contains( u"density_area_unit_scale"_s ) )
5602 sl->setDensityAreaUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( properties[u"density_area_unit_scale"_s].toString() ) );
5603
5604 if ( properties.contains( u"clip_points"_s ) )
5605 {
5606 sl->setClipPoints( properties[u"clip_points"_s].toInt() );
5607 }
5608
5609 return sl;
5610}
5611
5613{
5614 return u"RandomMarkerFill"_s;
5615}
5616
5618{
5619 mMarker->setColor( color );
5620 mColor = color;
5621}
5622
5624{
5625 return mMarker ? mMarker->color() : mColor;
5626}
5627
5629{
5630 mMarker->setRenderHints( mMarker->renderHints() | Qgis::SymbolRenderHint::IsSymbolLayerSubSymbol );
5631 mMarker->startRender( context.renderContext(), context.fields() );
5632}
5633
5635{
5636 mMarker->stopRender( context.renderContext() );
5637}
5638
5639void QgsRandomMarkerFillSymbolLayer::renderPolygon( const QPolygonF &points, const QVector<QPolygonF> *rings, QgsSymbolRenderContext &context )
5640{
5641 Part part;
5642 part.exterior = points;
5643 if ( rings )
5644 part.rings = *rings;
5645
5646 if ( mRenderingFeature )
5647 {
5648 // in the middle of rendering a possibly multi-part feature, so we collect all the parts and defer the actual rendering
5649 // until after we've received the final part
5650 mFeatureSymbolOpacity = context.opacity();
5651 mCurrentParts << part;
5652 }
5653 else
5654 {
5655 // not rendering a feature, so we can just render the polygon immediately
5656 const double prevOpacity = mMarker->opacity();
5657 mMarker->setOpacity( mMarker->opacity() * context.opacity() );
5658 const bool useSelectedColor = shouldRenderUsingSelectionColor( context );
5659 render( context.renderContext(), QVector< Part>() << part, context.feature() ? *context.feature() : QgsFeature(), useSelectedColor );
5660 mMarker->setOpacity( prevOpacity );
5661 }
5662}
5663
5664void QgsRandomMarkerFillSymbolLayer::render( QgsRenderContext &context, const QVector<QgsRandomMarkerFillSymbolLayer::Part> &parts, const QgsFeature &feature, bool selected )
5665{
5666 bool clipPoints = mClipPoints;
5668 {
5671 }
5672
5673 QVector< QgsGeometry > geometryParts;
5674 geometryParts.reserve( parts.size() );
5675 QPainterPath path;
5676
5677 for ( const Part &part : parts )
5678 {
5679 QgsGeometry geom = QgsGeometry::fromQPolygonF( part.exterior );
5680 if ( !geom.isNull() && !part.rings.empty() )
5681 {
5682 QgsPolygon *poly = qgsgeometry_cast< QgsPolygon * >( geom.get() );
5683 for ( const QPolygonF &ring : part.rings )
5684 {
5685 std::unique_ptr< QgsLineString > fromRing = QgsLineString::fromQPolygonF( ring );
5686 poly->addInteriorRing( fromRing.release() );
5687 }
5688 }
5689 if ( !geom.isGeosValid() )
5690 {
5691 geom = geom.buffer( 0, 0, context.feedback() );
5692 }
5693 geometryParts << geom;
5694
5695 if ( clipPoints )
5696 {
5697 path.addPolygon( part.exterior );
5698 for ( const QPolygonF &ring : part.rings )
5699 {
5700 path.addPolygon( ring );
5701 }
5702 }
5703 }
5704
5705 const QgsGeometry geom = geometryParts.count() != 1 ? QgsGeometry::unaryUnion( geometryParts, QgsGeometryParameters(), context.feedback() ) : geometryParts.at( 0 );
5706
5707 QgsScopedQPainterState painterState( context.painter(), QgsScopedQPainterState::InitialState::NoSave );
5708 if ( clipPoints )
5709 {
5710 painterState.save();
5711 context.painter()->setClipPath( path );
5712 }
5713
5714
5715 int count = mPointCount;
5717 {
5720 }
5721
5722 switch ( mCountMethod )
5723 {
5725 {
5726 double densityArea = mDensityArea;
5728 {
5731 }
5732 densityArea = context.convertToPainterUnits( std::sqrt( densityArea ), mDensityAreaUnit, mDensityAreaUnitScale );
5733 densityArea = std::pow( densityArea, 2 );
5734 count = std::max( 0.0, std::ceil( count * ( geom.area() / densityArea ) ) );
5735 break;
5736 }
5738 break;
5739 }
5740
5741 unsigned long seed = mSeed;
5743 {
5744 context.expressionContext().setOriginalValueVariable( static_cast< unsigned long long >( seed ) );
5746 }
5747
5748 QVector< QgsPointXY > randomPoints = geom.randomPointsInPolygon( count, seed );
5749#if 0
5750 // in some cases rendering from top to bottom is nice (e.g. randomised tree markers), but in other cases it's not wanted..
5751 // TODO consider exposing this as an option
5752 std::sort( randomPoints.begin(), randomPoints.end(), []( const QgsPointXY & a, const QgsPointXY & b )->bool
5753 {
5754 return a.y() < b.y();
5755 } );
5756#endif
5757 QgsExpressionContextScope *scope = new QgsExpressionContextScope();
5758 QgsExpressionContextScopePopper scopePopper( context.expressionContext(), scope );
5759 int pointNum = 0;
5760 const bool needsExpressionContext = mMarker->hasDataDefinedProperties();
5761
5762 const bool prevIsSubsymbol = context.flags() & Qgis::RenderContextFlag::RenderingSubSymbol;
5764
5765 for ( const QgsPointXY &p : std::as_const( randomPoints ) )
5766 {
5767 if ( needsExpressionContext )
5768 scope->addVariable( QgsExpressionContextScope::StaticVariable( QgsExpressionContext::EXPR_GEOMETRY_POINT_NUM, ++pointNum, true ) );
5769 mMarker->renderPoint( QPointF( p.x(), p.y() ), feature.isValid() ? &feature : nullptr, context, -1, selected );
5770 }
5771
5772 context.setFlag( Qgis::RenderContextFlag::RenderingSubSymbol, prevIsSubsymbol );
5773}
5774
5776{
5777 QVariantMap map;
5778 map.insert( u"count_method"_s, QString::number( static_cast< int >( mCountMethod ) ) );
5779 map.insert( u"point_count"_s, QString::number( mPointCount ) );
5780 map.insert( u"density_area"_s, QString::number( mDensityArea ) );
5781 map.insert( u"density_area_unit"_s, QgsUnitTypes::encodeUnit( mDensityAreaUnit ) );
5782 map.insert( u"density_area_unit_scale"_s, QgsSymbolLayerUtils::encodeMapUnitScale( mDensityAreaUnitScale ) );
5783 map.insert( u"seed"_s, QString::number( mSeed ) );
5784 map.insert( u"clip_points"_s, QString::number( mClipPoints ) );
5785 return map;
5786}
5787
5789{
5790 auto res = std::make_unique< QgsRandomMarkerFillSymbolLayer >( mPointCount, mCountMethod, mDensityArea, mSeed );
5791 res->mAngle = mAngle;
5792 res->mColor = mColor;
5793 res->setDensityAreaUnit( mDensityAreaUnit );
5794 res->setDensityAreaUnitScale( mDensityAreaUnitScale );
5795 res->mClipPoints = mClipPoints;
5796 res->setSubSymbol( mMarker->clone() );
5797 copyCommonProperties( res.get() );
5798 return res.release();
5799}
5800
5805
5807{
5809 return false;
5810
5811 // special case -- two QgsRandomMarkerFillSymbolLayer will render differently if they have
5812 // no seed value set.
5813 if ( mSeed == 0 )
5814 return false;
5815
5816 return true;
5817}
5818
5820{
5821 return mMarker.get();
5822}
5823
5825{
5826 if ( !symbol || symbol->type() != Qgis::SymbolType::Marker )
5827 {
5828 delete symbol;
5829 return false;
5830 }
5831
5832 mMarker.reset( static_cast<QgsMarkerSymbol *>( symbol ) );
5833 mColor = mMarker->color();
5834 return true;
5835}
5836
5838{
5839 QSet<QString> attributes = QgsFillSymbolLayer::usedAttributes( context );
5840
5841 if ( mMarker )
5842 attributes.unite( mMarker->usedAttributes( context ) );
5843
5844 return attributes;
5845}
5846
5848{
5850 return true;
5851 if ( mMarker && mMarker->hasDataDefinedProperties() )
5852 return true;
5853 return false;
5854}
5855
5857{
5858 return mPointCount;
5859}
5860
5862{
5863 mPointCount = pointCount;
5864}
5865
5867{
5868 return mSeed;
5869}
5870
5872{
5873 mSeed = seed;
5874}
5875
5877{
5878 return mClipPoints;
5879}
5880
5882{
5883 mClipPoints = clipPoints;
5884}
5885
5887{
5888 return mCountMethod;
5889}
5890
5892{
5893 mCountMethod = method;
5894}
5895
5897{
5898 return mDensityArea;
5899}
5900
5902{
5903 mDensityArea = area;
5904}
5905
5907{
5908 installMasks( context, true );
5909
5910 mRenderingFeature = true;
5911 mCurrentParts.clear();
5912}
5913
5915{
5916 mRenderingFeature = false;
5917
5918 const double prevOpacity = mMarker->opacity();
5919 mMarker->setOpacity( mMarker->opacity() * mFeatureSymbolOpacity );
5920
5921 render( context, mCurrentParts, feature, false );
5922
5923 mFeatureSymbolOpacity = 1;
5924 mMarker->setOpacity( prevOpacity );
5925
5926 removeMasks( context, true );
5927}
5928
5929
5931{
5932 mDensityAreaUnit = unit;
5933 if ( mMarker )
5934 {
5935 mMarker->setOutputUnit( unit );
5936 }
5937}
5938
5940{
5941 if ( mMarker )
5942 {
5943 return mMarker->outputUnit();
5944 }
5945 return Qgis::RenderUnit::Unknown; //mOutputUnit;
5946}
5947
5949{
5950 if ( mMarker )
5951 {
5952 return mMarker->usesMapUnits();
5953 }
5954 return false;
5955}
5956
5958{
5959 if ( mMarker )
5960 {
5961 mMarker->setMapUnitScale( scale );
5962 }
5963}
5964
5966{
5967 if ( mMarker )
5968 {
5969 return mMarker->mapUnitScale();
5970 }
5971 return QgsMapUnitScale();
5972}
@ PreferVector
Prefer vector-based rendering, when the result will still be visually near-identical to a raster-base...
Definition qgis.h:2918
MarkerClipMode
Marker clipping modes.
Definition qgis.h:3499
@ CompletelyWithin
Render complete markers wherever the completely fall within the polygon shape.
Definition qgis.h:3503
@ NoClipping
No clipping, render complete markers.
Definition qgis.h:3500
@ Shape
Clip to polygon shape.
Definition qgis.h:3501
@ CentroidWithin
Render complete markers wherever their centroid falls within the polygon shape.
Definition qgis.h:3502
@ IsSymbolLayerSubSymbol
Symbol is being rendered as a sub-symbol of a QgsSymbolLayer.
Definition qgis.h:832
LineClipMode
Line clipping modes.
Definition qgis.h:3513
@ NoClipping
Lines are not clipped, will extend to shape's bounding box.
Definition qgis.h:3516
@ ClipPainterOnly
Applying clipping on the painter only (i.e. line endpoints will coincide with polygon bounding box,...
Definition qgis.h:3514
@ ClipToIntersection
Clip lines to intersection with polygon shape (slower) (i.e. line endpoints will coincide with polygo...
Definition qgis.h:3515
GradientColorSource
Gradient color sources.
Definition qgis.h:3428
@ ColorRamp
Gradient color ramp.
Definition qgis.h:3430
@ SimpleTwoColor
Simple two color gradient.
Definition qgis.h:3429
@ CanCalculateMaskGeometryPerFeature
If present, indicates that mask geometry can safely be calculated per feature for the symbol layer....
Definition qgis.h:964
GradientSpread
Gradient spread options, which control how gradients are rendered outside of their start and end poin...
Definition qgis.h:3472
@ Repeat
Repeat gradient.
Definition qgis.h:3475
@ Reflect
Reflect gradient.
Definition qgis.h:3474
@ Pad
Pad out gradient using colors at endpoint of gradient.
Definition qgis.h:3473
@ Png
Export complex styles to separate PNG files for better compatibility with OGC servers.
Definition qgis.h:760
PointCountMethod
Methods which define the number of points randomly filling a polygon.
Definition qgis.h:3487
@ Absolute
The point count is used as an absolute count of markers.
Definition qgis.h:3488
@ DensityBased
The point count is part of a marker density count.
Definition qgis.h:3489
QFlags< SymbolLayerFlag > SymbolLayerFlags
Symbol layer flags.
Definition qgis.h:969
RenderUnit
Rendering size units.
Definition qgis.h:5770
@ Percentage
Percentage of another measurement (e.g., canvas size, feature size).
Definition qgis.h:5774
@ Unknown
Mixed or unknown units.
Definition qgis.h:5777
@ MapUnits
Map units.
Definition qgis.h:5772
@ Pixels
Pixels.
Definition qgis.h:5773
@ MetersInMapUnits
Meters value as Map units.
Definition qgis.h:5778
@ RenderingSubSymbol
Set whenever a sub-symbol of a parent symbol is currently being rendered. Can be used during symbol a...
Definition qgis.h:2993
@ RenderSymbolPreview
The render is for a symbol preview only and map based properties may not be available,...
Definition qgis.h:2988
@ RenderMapTile
Draw map such that there are no problems between adjacent tiles.
Definition qgis.h:2983
@ RenderLayerTree
The render is for a layer tree display where map based properties are not available and where avoidan...
Definition qgis.h:2999
@ HighQualityImageTransforms
Enable high quality image transformations, which results in better appearance of scaled or rotated ra...
Definition qgis.h:2994
@ RenderBlocking
Render and load remote sources in the same thread to ensure rendering remote sources (svg and images)...
Definition qgis.h:2987
GradientType
Gradient types.
Definition qgis.h:3442
@ Linear
Linear gradient.
Definition qgis.h:3443
@ Conical
Conical (polar) gradient.
Definition qgis.h:3445
@ Radial
Radial (circular) gradient.
Definition qgis.h:3444
QFlags< SymbolRenderHint > SymbolRenderHints
Symbol render hints.
Definition qgis.h:838
@ Marker
Marker symbol.
Definition qgis.h:672
@ Line
Line symbol.
Definition qgis.h:673
SymbolCoordinateReference
Symbol coordinate reference modes.
Definition qgis.h:3457
@ Feature
Relative to feature/shape being rendered.
Definition qgis.h:3458
@ Viewport
Relative to the whole viewport/output device.
Definition qgis.h:3459
QColor valueAsColor(int key, const QgsExpressionContext &context, const QColor &defaultColor=QColor(), bool *ok=nullptr) const
Calculates the current value of the property with the specified key and interprets it as a color.
bool valueAsBool(int key, const QgsExpressionContext &context, bool defaultValue=false, bool *ok=nullptr) const
Calculates the current value of the property with the specified key and interprets it as an boolean.
static QgsImageCache * imageCache()
Returns the application's image cache, used for caching resampled versions of raster images.
static QgsSvgCache * svgCache()
Returns the application's SVG cache, used for caching SVG images and handling parameter replacement w...
QSet< QString > usedAttributes(const QgsRenderContext &context) const override
Returns the set of attributes referenced by the layer.
QVariantMap properties() const override
Should be reimplemented by subclasses to return a string map that contains the configuration informat...
QgsSymbol * subSymbol() override
Returns the symbol's sub symbol, if present.
Qgis::RenderUnit outputUnit() const override
Returns the units to use for sizes and widths within the symbol layer.
void setMapUnitScale(const QgsMapUnitScale &scale) override
bool canCauseArtifactsBetweenAdjacentTiles() const override
Returns true if the symbol layer rendering can cause visible artifacts across a single feature when t...
bool setSubSymbol(QgsSymbol *symbol) final
Sets layer's subsymbol. takes ownership of the passed symbol.
QgsMapUnitScale mapUnitScale() const override
static std::unique_ptr< QgsSymbolLayer > create(const QVariantMap &properties=QVariantMap())
Creates a new QgsCentroidFillSymbolLayer using the specified properties map containing symbol propert...
void startFeatureRender(const QgsFeature &feature, QgsRenderContext &context) override
Called before the layer will be rendered for a particular feature.
std::unique_ptr< QgsMarkerSymbol > mMarker
QString layerType() const override
Returns a string that represents this layer type.
void setColor(const QColor &color) override
Sets the "representative" color for the symbol layer.
bool pointOnAllParts() const
Returns whether a point is drawn for all parts or only on the biggest part of multi-part features.
void renderPolygon(const QPolygonF &points, const QVector< QPolygonF > *rings, QgsSymbolRenderContext &context) override
Renders the fill symbol layer for the polygon whose outer ring is defined by points,...
void startRender(QgsSymbolRenderContext &context) override
Called before a set of rendering operations commences on the supplied render context.
bool hasDataDefinedProperties() const override
Returns true if the symbol layer (or any of its sub-symbols) contains data defined properties.
void stopFeatureRender(const QgsFeature &feature, QgsRenderContext &context) override
Called after the layer has been rendered for a particular feature.
void setOutputUnit(Qgis::RenderUnit unit) override
Sets the units to use for sizes and widths within the symbol layer.
bool usesMapUnits() const override
Returns true if the symbol layer has any components which use map unit based sizes.
bool clipPoints() const
Returns true if point markers should be clipped to the polygon boundary.
QgsCentroidFillSymbolLayer * clone() const override
Shall be reimplemented by subclasses to create a deep copy of the instance.
Q_DECL_DEPRECATED void toSld(QDomDocument &doc, QDomElement &element, const QVariantMap &props) const override
Saves the symbol layer as SLD.
static std::unique_ptr< QgsSymbolLayer > createFromSld(QDomElement &element)
~QgsCentroidFillSymbolLayer() override
void stopRender(QgsSymbolRenderContext &context) override
Called after a set of rendering operations has finished on the supplied render context.
QColor color() const override
Returns the "representative" color of the symbol layer.
bool clipOnCurrentPartOnly() const
Returns true if point markers should be clipped to the current part boundary only.
Abstract base class for color ramps.
virtual QColor color(double value) const =0
Returns the color corresponding to a specified value.
virtual QString type() const =0
Returns a string representing the color ramp type.
static QColor colorFromString(const QString &string)
Decodes a string into a color value.
static QString colorToString(const QColor &color)
Encodes a color into a string value.
static QString typeString()
Returns the string identifier for QgsCptCityColorRamp.
static std::unique_ptr< QgsColorRamp > create(const QVariantMap &properties=QVariantMap())
Creates the symbol layer.
double area() const override
Returns the planar, 2-dimensional area of the geometry.
RAII class to pop scope from an expression context on destruction.
Single scope for storing variables and functions for use within a QgsExpressionContext.
void addVariable(const QgsExpressionContextScope::StaticVariable &variable)
Adds a variable into the context scope.
static const QString EXPR_GEOMETRY_POINT_NUM
Inbuilt variable name for point number variable.
void setOriginalValueVariable(const QVariant &value)
Sets the original value variable value for the context.
The feature class encapsulates a single feature including its unique ID, geometry and a list of field...
Definition qgsfeature.h:60
bool isValid() const
Returns the validity of this feature.
bool isCanceled() const
Tells whether the operation has been canceled already.
Definition qgsfeedback.h:56
void _renderPolygon(QPainter *p, const QPolygonF &points, const QVector< QPolygonF > *rings, QgsSymbolRenderContext &context)
Default method to render polygon.
double angle() const
Returns the rotation angle of the fill symbol, in degrees clockwise.
Encapsulates parameters under which a geometry operation is performed.
A geometry is the spatial representation of a feature.
QVector< QgsPointXY > randomPointsInPolygon(int count, const std::function< bool(const QgsPointXY &) > &acceptPoint, unsigned long seed=0, QgsFeedback *feedback=nullptr, int maxTriesPerPoint=0) const
Returns a list of count random points generated inside a (multi)polygon geometry (if acceptPoint is s...
static QgsGeometry fromRect(const QgsRectangle &rect)
Creates a new geometry from a QgsRectangle.
static QgsGeometry fromQPolygonF(const QPolygonF &polygon)
Construct geometry from a QPolygonF.
QgsAbstractGeometry * get()
Returns a modifiable (non-const) reference to the underlying abstract geometry primitive.
const QgsAbstractGeometry * constGet() const
Returns a non-modifiable (const) reference to the underlying abstract geometry primitive.
bool isGeosValid(Qgis::GeometryValidityFlags flags=Qgis::GeometryValidityFlags()) const
Checks validity of the geometry using GEOS.
double area() const
Returns the planar, 2-dimensional area of the geometry.
static QgsGeometry unaryUnion(const QVector< QgsGeometry > &geometries, const QgsGeometryParameters &parameters=QgsGeometryParameters(), QgsFeedback *feedback=nullptr)
Compute the unary union on a list of geometries.
QgsGeometry buffer(double distance, int segments, QgsFeedback *feedback=nullptr) const
Returns a buffer region around this geometry having the given width and with a specified number of se...
static std::unique_ptr< QgsGeometryEngine > createGeometryEngine(const QgsAbstractGeometry *geometry, double precision=0.0, Qgis::GeosCreationFlags flags=Qgis::GeosCreationFlag::SkipEmptyInteriorRings)
Creates and returns a new geometry engine representing the specified geometry using precision on a gr...
static std::unique_ptr< QgsColorRamp > create(const QVariantMap &properties=QVariantMap())
Creates a new QgsColorRamp from a map of properties.
static QString typeString()
Returns the string identifier for QgsGradientColorRamp.
void addStopsToGradient(QGradient *gradient, double opacity=1) const
Copy color ramp stops to a QGradient.
void setColorRamp(QgsColorRamp *ramp)
Sets the color ramp used for the gradient fill.
Qgis::RenderUnit outputUnit() const override
Returns the units to use for sizes and widths within the symbol layer.
QColor color2() const
Returns the color for endpoint of gradient, only used if the gradient color type is set to SimpleTwoC...
void renderPolygon(const QPolygonF &points, const QVector< QPolygonF > *rings, QgsSymbolRenderContext &context) override
Renders the fill symbol layer for the polygon whose outer ring is defined by points,...
void stopRender(QgsSymbolRenderContext &context) override
Called after a set of rendering operations has finished on the supplied render context.
bool canCauseArtifactsBetweenAdjacentTiles() const override
Returns true if the symbol layer rendering can cause visible artifacts across a single feature when t...
QgsGradientFillSymbolLayer * clone() const override
Shall be reimplemented by subclasses to create a deep copy of the instance.
QgsMapUnitScale mapUnitScale() const override
bool usesMapUnits() const override
Returns true if the symbol layer has any components which use map unit based sizes.
Qgis::SymbolCoordinateReference coordinateMode() const
Returns the coordinate mode for gradient, which controls how the gradient stops are positioned.
static std::unique_ptr< QgsSymbolLayer > create(const QVariantMap &properties=QVariantMap())
Creates a new QgsGradientFillSymbolLayer using the specified properties map containing symbol propert...
QVariantMap properties() const override
Should be reimplemented by subclasses to return a string map that contains the configuration informat...
Qgis::SymbolCoordinateReference mCoordinateMode
QgsGradientFillSymbolLayer(const QColor &color=DEFAULT_SIMPLEFILL_COLOR, const QColor &color2=Qt::white, Qgis::GradientColorSource gradientColorType=Qgis::GradientColorSource::SimpleTwoColor, Qgis::GradientType gradientType=Qgis::GradientType::Linear, Qgis::SymbolCoordinateReference coordinateMode=Qgis::SymbolCoordinateReference::Feature, Qgis::GradientSpread gradientSpread=Qgis::GradientSpread::Pad)
Constructor for QgsGradientFillSymbolLayer.
void setMapUnitScale(const QgsMapUnitScale &scale) override
double estimateMaxBleed(const QgsRenderContext &context) const override
Returns the estimated maximum distance which the layer style will bleed outside the drawn shape when ...
Qgis::GradientSpread mGradientSpread
void setOutputUnit(Qgis::RenderUnit unit) override
Sets the units to use for sizes and widths within the symbol layer.
QPointF referencePoint1() const
Returns the starting point of gradient fill, in the range [0,0] - [1,1].
Qgis::GradientSpread gradientSpread() const
Returns the gradient spread mode, which controls how the gradient behaves outside of the predefined s...
Qgis::GradientColorSource gradientColorType() const
Returns the gradient color mode, which controls how gradient color stops are created.
QPointF offset() const
Returns the offset by which polygons will be translated during rendering.
Qgis::GradientColorSource mGradientColorType
void startRender(QgsSymbolRenderContext &context) override
Called before a set of rendering operations commences on the supplied render context.
Qgis::SymbolLayerFlags flags() const override
Returns flags which control the symbol layer's behavior.
QString layerType() const override
Returns a string that represents this layer type.
Qgis::GradientType gradientType() const
Returns the type of gradient, e.g., linear or radial.
QPointF referencePoint2() const
Returns the end point of gradient fill, in the range [0,0] - [1,1].
std::unique_ptr< QgsColorRamp > mGradientRamp
QSize originalSize(const QString &path, bool blocking=false) const
Returns the original size (in pixels) of the image at the specified path.
QImage pathAsImage(const QString &path, const QSize size, const bool keepAspectRatio, const double opacity, bool &fitsInCache, bool blocking=false, double targetDpi=96, int frameNumber=-1, bool *isMissing=nullptr)
Returns the specified path rendered as an image.
QgsMapUnitScale mStrokeWidthMapUnitScale
Qgis::SymbolCoordinateReference coordinateReference() const
Returns the coordinate reference mode for fill which controls how the top left corner of the image fi...
double mStrokeWidth
Stroke width.
Qgis::SymbolCoordinateReference mCoordinateReference
QgsMapUnitScale mapUnitScale() const override
Qt::PenStyle dxfPenStyle() const override
Gets pen style.
Qgis::RenderUnit mStrokeWidthUnit
void setOutputUnit(Qgis::RenderUnit unit) override
Sets the units to use for sizes and widths within the symbol layer.
void setMapUnitScale(const QgsMapUnitScale &scale) override
virtual void applyDataDefinedSettings(QgsSymbolRenderContext &context)
Applies data defined settings prior to generating the fill symbol brush.
Qgis::RenderUnit outputUnit() const override
Returns the units to use for sizes and widths within the symbol layer.
double dxfWidth(QgsSymbolRenderContext &context) const override
Gets line width.
void renderPolygon(const QPolygonF &points, const QVector< QPolygonF > *rings, QgsSymbolRenderContext &context) override
Renders the fill symbol layer for the polygon whose outer ring is defined by points,...
QVariantMap properties() const override
Should be reimplemented by subclasses to return a string map that contains the configuration informat...
~QgsImageFillSymbolLayer() override
virtual bool applyBrushTransformFromContext(QgsSymbolRenderContext *context=nullptr) const
Returns true if the image brush should be transformed using the render context's texture origin.
static void multiplyOpacity(QImage &image, double factor, QgsFeedback *feedback=nullptr)
Multiplies opacity of image pixel values by a factor.
static void stackBlur(QImage &image, int radius, bool alphaOnly=false, QgsFeedback *feedback=nullptr)
Performs a stack blur on an image.
Qgis::RenderUnit outputUnit() const override
Returns the units to use for sizes and widths within the symbol layer.
QgsMapUnitScale mapUnitScale() const override
void startRender(QgsSymbolRenderContext &context) override
Called before a set of rendering operations commences on the supplied render context.
QString layerType() const override
Returns a string that represents this layer type.
QgsLinePatternFillSymbolLayer * clone() const override
Shall be reimplemented by subclasses to create a deep copy of the instance.
void stopFeatureRender(const QgsFeature &feature, QgsRenderContext &context) override
Called after the layer has been rendered for a particular feature.
void startFeatureRender(const QgsFeature &feature, QgsRenderContext &context) override
Called before the layer will be rendered for a particular feature.
QColor color() const override
Returns the "representative" color of the symbol layer.
Q_DECL_DEPRECATED void toSld(QDomDocument &doc, QDomElement &element, const QVariantMap &props) const override
Saves the symbol layer as SLD.
double lineWidth() const
Returns the width of the line subsymbol used to render the parallel lines in the fill.
bool usesMapUnits() const override
Returns true if the symbol layer has any components which use map unit based sizes.
void setMapUnitScale(const QgsMapUnitScale &scale) override
Qgis::LineClipMode clipMode() const
Returns the line clipping mode, which defines how lines are clipped at the edges of shapes.
double lineAngle() const
Returns the angle for the parallel lines used to fill the symbol.
void setLineWidth(double w)
Sets the width of the line subsymbol used to render the parallel lines in the fill.
void renderPolygon(const QPolygonF &points, const QVector< QPolygonF > *rings, QgsSymbolRenderContext &context) override
Renders the fill symbol layer for the polygon whose outer ring is defined by points,...
QSet< QString > usedAttributes(const QgsRenderContext &context) const override
Returns the set of attributes referenced by the layer.
void applyDataDefinedSettings(QgsSymbolRenderContext &context) override
Applies data defined settings prior to generating the fill symbol brush.
bool setSubSymbol(QgsSymbol *symbol) override
Sets layer's subsymbol. takes ownership of the passed symbol.
static std::unique_ptr< QgsSymbolLayer > createFromSld(QDomElement &element)
Creates a new QgsLinePatternFillSymbolLayer from a SLD element.
QgsSymbol * subSymbol() override
Returns the symbol's sub symbol, if present.
bool hasDataDefinedProperties() const override
Returns true if the symbol layer (or any of its sub-symbols) contains data defined properties.
QVariantMap properties() const override
Should be reimplemented by subclasses to return a string map that contains the configuration informat...
void setColor(const QColor &c) override
Sets the "representative" color for the symbol layer.
QImage toTiledPatternImage() const override
Renders the symbol layer as an image that can be used as a seamless pattern fill for polygons,...
double offset() const
Returns the offset distance for lines within the fill, which is the distance to offset the parallel l...
double distance() const
Returns the distance between lines in the fill pattern.
void setOutputUnit(Qgis::RenderUnit unit) override
Sets the units to use for sizes and widths within the symbol layer.
QString ogrFeatureStyleWidth(double widthScaleFactor) const
void stopRender(QgsSymbolRenderContext &context) override
Called after a set of rendering operations has finished on the supplied render context.
~QgsLinePatternFillSymbolLayer() override
static std::unique_ptr< QgsSymbolLayer > create(const QVariantMap &properties=QVariantMap())
Creates a new QgsLinePatternFillSymbolLayer from a properties map.
double estimateMaxBleed(const QgsRenderContext &context) const override
Returns the estimated maximum distance which the layer style will bleed outside the drawn shape when ...
Line string geometry type, with support for z-dimension and m-values.
static std::unique_ptr< QgsLineString > fromQPolygonF(const QPolygonF &polygon)
Returns a new linestring from a QPolygonF polygon input.
QPolygonF asQPolygonF() const override
Returns a QPolygonF representing the points.
A line symbol type, for rendering LineString and MultiLineString geometries.
double mapUnitsPerPixel() const
Returns the current map units per pixel.
Struct for storing maximum and minimum scales for measurements in map units.
Abstract base class for marker symbol layers.
A marker symbol type, for rendering Point and MultiPoint geometries.
static void logMessage(const QString &message, const QString &tag=QString(), Qgis::MessageLevel level=Qgis::MessageLevel::Warning, bool notifyUser=true, const char *file=__builtin_FILE(), const char *function=__builtin_FUNCTION(), int line=__builtin_LINE(), Qgis::StringFormat format=Qgis::StringFormat::PlainText)
Adds a message to the log instance (and creates it if necessary).
Resolves relative paths into absolute paths and vice versa.
QString writePath(const QString &filename) const
Prepare a filename to save it to the project file.
QString readPath(const QString &filename) const
Turn filename read from the project file to an absolute path.
QgsMapUnitScale mapUnitScale() const override
void stopRender(QgsSymbolRenderContext &context) override
Called after a set of rendering operations has finished on the supplied render context.
void renderPolygon(const QPolygonF &points, const QVector< QPolygonF > *rings, QgsSymbolRenderContext &context) override
Renders the fill symbol layer for the polygon whose outer ring is defined by points,...
double distanceX() const
Returns the horizontal distance between rendered markers in the fill.
QImage toTiledPatternImage() const override
Renders the symbol layer as an image that can be used as a seamless pattern fill for polygons,...
double displacementY() const
Returns the vertical displacement for odd numbered columns in the pattern.
void setColor(const QColor &c) override
Sets the "representative" color for the symbol layer.
void startFeatureRender(const QgsFeature &feature, QgsRenderContext &context) override
Called before the layer will be rendered for a particular feature.
unsigned long seed() const
Returns the random number seed to use when randomly shifting points, or 0 if a truly random sequence ...
Qgis::MarkerClipMode clipMode() const
Returns the marker clipping mode, which defines how markers are clipped at the edges of shapes.
static std::unique_ptr< QgsSymbolLayer > create(const QVariantMap &properties=QVariantMap())
Creates a new QgsPointPatternFillSymbolLayer using the specified properties map containing symbol pro...
bool hasDataDefinedProperties() const override
Returns true if the symbol layer (or any of its sub-symbols) contains data defined properties.
double offsetY() const
Returns the vertical offset values for points in the pattern.
QgsSymbol * subSymbol() override
Returns the symbol's sub symbol, if present.
void setMapUnitScale(const QgsMapUnitScale &scale) override
double estimateMaxBleed(const QgsRenderContext &context) const override
Returns the estimated maximum distance which the layer style will bleed outside the drawn shape when ...
void startRender(QgsSymbolRenderContext &context) override
Called before a set of rendering operations commences on the supplied render context.
QString layerType() const override
Returns a string that represents this layer type.
void applyDataDefinedSettings(QgsSymbolRenderContext &context) override
Applies data defined settings prior to generating the fill symbol brush.
QVariantMap properties() const override
Should be reimplemented by subclasses to return a string map that contains the configuration informat...
void stopFeatureRender(const QgsFeature &feature, QgsRenderContext &context) override
Called after the layer has been rendered for a particular feature.
QColor color() const override
Returns the "representative" color of the symbol layer.
static std::unique_ptr< QgsSymbolLayer > createFromSld(QDomElement &element)
Q_DECL_DEPRECATED void toSld(QDomDocument &doc, QDomElement &element, const QVariantMap &props) const override
Saves the symbol layer as SLD.
double offsetX() const
Returns the horizontal offset values for points in the pattern.
Qgis::RenderUnit outputUnit() const override
Returns the units to use for sizes and widths within the symbol layer.
std::unique_ptr< QgsMarkerSymbol > mMarkerSymbol
bool usesMapUnits() const override
Returns true if the symbol layer has any components which use map unit based sizes.
QgsPointPatternFillSymbolLayer * clone() const override
Shall be reimplemented by subclasses to create a deep copy of the instance.
double displacementX() const
Returns the horizontal displacement for odd numbered rows in the pattern.
void setOutputUnit(Qgis::RenderUnit unit) override
Sets the units to use for sizes and widths within the symbol layer.
QSet< QString > usedAttributes(const QgsRenderContext &context) const override
Returns the set of attributes referenced by the layer.
~QgsPointPatternFillSymbolLayer() override
bool setSubSymbol(QgsSymbol *symbol) override
Sets layer's subsymbol. takes ownership of the passed symbol.
double distanceY() const
Returns the vertical distance between rendered markers in the fill.
Point geometry type, with support for z-dimension and m-values.
Definition qgspoint.h:53
Polygon geometry type.
Definition qgspolygon.h:37
void addInteriorRing(QgsCurve *ring) override
Adds an interior ring to the geometry (takes ownership).
static QgsProject * instance()
Returns the QgsProject singleton instance.
QgsPathResolver pathResolver() const
Returns path resolver object with considering whether the project uses absolute or relative paths and...
bool isActive(int key) const final
Returns true if the collection contains an active property with the specified key.
static QVariantMap propertyMapToVariantMap(const QMap< QString, QgsProperty > &propertyMap)
Convert a map of QgsProperty to a map of QVariant This is useful to save a map of properties.
static QMap< QString, QgsProperty > variantMapToPropertyMap(const QVariantMap &variantMap)
Convert a map of QVariant to a map of QgsProperty This is useful to restore a map of properties.
~QgsRandomMarkerFillSymbolLayer() override
bool setSubSymbol(QgsSymbol *symbol) final
Sets layer's subsymbol. takes ownership of the passed symbol.
int pointCount() const
Returns the count of random points to render in the fill.
bool usesMapUnits() const override
Returns true if the symbol layer has any components which use map unit based sizes.
void startFeatureRender(const QgsFeature &feature, QgsRenderContext &context) override
Called before the layer will be rendered for a particular feature.
QgsRandomMarkerFillSymbolLayer(int pointCount=10, Qgis::PointCountMethod method=Qgis::PointCountMethod::Absolute, double densityArea=250.0, unsigned long seed=0)
Constructor for QgsRandomMarkerFillSymbolLayer, with the specified pointCount.
unsigned long seed() const
Returns the random number seed to use when generating points, or 0 if a truly random sequence will be...
void renderPolygon(const QPolygonF &points, const QVector< QPolygonF > *rings, QgsSymbolRenderContext &context) override
Renders the fill symbol layer for the polygon whose outer ring is defined by points,...
QString layerType() const override
Returns a string that represents this layer type.
QVariantMap properties() const override
Should be reimplemented by subclasses to return a string map that contains the configuration informat...
QgsRandomMarkerFillSymbolLayer * clone() const override
Shall be reimplemented by subclasses to create a deep copy of the instance.
Qgis::RenderUnit outputUnit() const override
Returns the units to use for sizes and widths within the symbol layer.
void setMapUnitScale(const QgsMapUnitScale &scale) override
bool hasDataDefinedProperties() const override
Returns true if the symbol layer (or any of its sub-symbols) contains data defined properties.
void stopFeatureRender(const QgsFeature &feature, QgsRenderContext &context) override
Called after the layer has been rendered for a particular feature.
void startRender(QgsSymbolRenderContext &context) override
Called before a set of rendering operations commences on the supplied render context.
static std::unique_ptr< QgsSymbolLayer > create(const QVariantMap &properties=QVariantMap())
Creates a new QgsRandomMarkerFillSymbolLayer using the specified properties map containing symbol pro...
void setCountMethod(Qgis::PointCountMethod method)
Sets the count method used to randomly fill the polygon.
bool clipPoints() const
Returns true if point markers should be clipped to the polygon boundary.
bool canCauseArtifactsBetweenAdjacentTiles() const override
Returns true if the symbol layer rendering can cause visible artifacts across a single feature when t...
void setClipPoints(bool clipped)
Sets whether point markers should be clipped to the polygon boundary.
QgsSymbol * subSymbol() override
Returns the symbol's sub symbol, if present.
void stopRender(QgsSymbolRenderContext &context) override
Called after a set of rendering operations has finished on the supplied render context.
QColor color() const override
Returns the "representative" color of the symbol layer.
void setSeed(unsigned long seed)
Sets the random number seed to use when generating points, or 0 if a truly random sequence will be us...
QSet< QString > usedAttributes(const QgsRenderContext &context) const override
Returns the set of attributes referenced by the layer.
void setPointCount(int count)
Sets the count of random points to render in the fill.
Qgis::PointCountMethod countMethod() const
Returns the count method used to randomly fill the polygon.
double densityArea() const
Returns the density area used to count the number of points to randomly fill the polygon.
bool rendersIdenticallyTo(const QgsSymbolLayer *other) const override
Returns true if this symbol layer will always render identically to an other symbol layer.
void setColor(const QColor &color) override
Sets the "representative" color for the symbol layer.
void setDensityArea(double area)
Sets the density area used to count the number of points to randomly fill the polygon.
void setOutputUnit(Qgis::RenderUnit unit) override
Sets the units to use for sizes and widths within the symbol layer.
QgsMapUnitScale mapUnitScale() const override
void applyDataDefinedSettings(QgsSymbolRenderContext &context) override
Applies data defined settings prior to generating the fill symbol brush.
void stopRender(QgsSymbolRenderContext &context) override
Called after a set of rendering operations has finished on the supplied render context.
double width() const
Returns the width used for scaling the image used in the fill.
double estimateMaxBleed(const QgsRenderContext &context) const override
Returns the estimated maximum distance which the layer style will bleed outside the drawn shape when ...
Qgis::SymbolLayerFlags flags() const override
Returns flags which control the symbol layer's behavior.
void renderPolygon(const QPolygonF &points, const QVector< QPolygonF > *rings, QgsSymbolRenderContext &context) override
Renders the fill symbol layer for the polygon whose outer ring is defined by points,...
QString layerType() const override
Returns a string that represents this layer type.
void setOutputUnit(Qgis::RenderUnit unit) override
Sets the units to use for sizes and widths within the symbol layer.
QgsRasterFillSymbolLayer(const QString &imageFilePath=QString())
Constructor for QgsRasterFillSymbolLayer, using a raster fill from the specified imageFilePath.
double opacity() const
Returns the opacity for the raster image used in the fill.
~QgsRasterFillSymbolLayer() override
void setOpacity(double opacity)
Sets the opacity for the raster image used in the fill.
QColor color() const override
Returns the "representative" color of the symbol layer.
QVariantMap properties() const override
Should be reimplemented by subclasses to return a string map that contains the configuration informat...
void startRender(QgsSymbolRenderContext &context) override
Called before a set of rendering operations commences on the supplied render context.
QString imageFilePath() const
The path to the raster image used for the fill.
void setImageFilePath(const QString &imagePath)
Sets the path to the raster image used for the fill.
double height() const
Returns the height used for scaling the image used in the fill.
static std::unique_ptr< QgsSymbolLayer > create(const QVariantMap &properties=QVariantMap())
Creates a new QgsRasterFillSymbolLayer from a properties map.
static void resolvePaths(QVariantMap &properties, const QgsPathResolver &pathResolver, bool saving)
Turns relative paths in properties map to absolute when reading and vice versa when writing.
QPointF offset() const
Returns the offset for the fill.
static std::unique_ptr< QgsSymbolLayer > createFromSld(QDomElement &element)
Creates a new QgsRasterFillSymbolLayer from a SLD element.
bool usesMapUnits() const override
Returns true if the symbol layer has any components which use map unit based sizes.
bool setSubSymbol(QgsSymbol *symbol) override
Sets layer's subsymbol. takes ownership of the passed symbol.
QgsRasterFillSymbolLayer * clone() const override
Shall be reimplemented by subclasses to create a deep copy of the instance.
bool applyBrushTransformFromContext(QgsSymbolRenderContext *context=nullptr) const override
Returns true if the image brush should be transformed using the render context's texture origin.
void setCoordinateMode(Qgis::SymbolCoordinateReference mode)
Set the coordinate mode for fill.
A rectangle specified with double values.
QgsPointXY center
Contains information about the context of a rendering operation.
double scaleFactor() const
Returns the scaling factor for the render to convert painter units to physical sizes.
double convertToMapUnits(double size, Qgis::RenderUnit unit, const QgsMapUnitScale &scale=QgsMapUnitScale()) const
Converts a size from the specified units to map units.
void setScaleFactor(double factor)
Sets the scaling factor for the render to convert painter units to physical sizes.
QSet< QString > disabledSymbolLayersV2() const
When rendering a map layer in a second pass (for selective masking), some symbol layers may be disabl...
double convertToPainterUnits(double size, Qgis::RenderUnit unit, const QgsMapUnitScale &scale=QgsMapUnitScale(), Qgis::RenderSubcomponentProperty property=Qgis::RenderSubcomponentProperty::Generic) const
Converts a size from the specified units to painter units (pixels).
QPainter * painter()
Returns the destination QPainter for the render operation.
double rendererScale() const
Returns the renderer map scale.
void setPainterFlagsUsingContext(QPainter *painter=nullptr) const
Sets relevant flags on a destination painter, using the flags and settings currently defined for the ...
QgsExpressionContext & expressionContext()
Gets the expression context.
void setDisabledSymbolLayersV2(const QSet< QString > &symbolLayers)
When rendering a map layer in a second pass (for selective masking), some symbol layers may be disabl...
void setRasterizedRenderingPolicy(Qgis::RasterizedRenderingPolicy policy)
Sets the policy controlling when rasterisation of content during renders is permitted.
void setFlag(Qgis::RenderContextFlag flag, bool on=true)
Enable or disable a particular flag (other flags are not affected).
const QgsMapToPixel & mapToPixel() const
Returns the context's map to pixel transform, which transforms between map coordinates and device coo...
QColor selectionColor() const
Returns the color to use when rendering selected features.
void setMapToPixel(const QgsMapToPixel &mtp)
Sets the context's map to pixel transform, which transforms between map coordinates and device coordi...
QgsFeedback * feedback() const
Returns the feedback object that can be queried regularly during rendering to check if rendering shou...
QPointF textureOrigin() const
Returns the texture origin, which should be used as a brush transform when rendering using QBrush obj...
void setPainter(QPainter *p)
Sets the destination QPainter for the render operation.
bool renderingStopped() const
Returns true if the rendering operation has been stopped and any ongoing rendering should be canceled...
static QgsRenderContext fromQPainter(QPainter *painter)
Creates a default render context given a pixel based QPainter destination.
void setExpressionContext(const QgsExpressionContext &context)
Sets the expression context.
void setRendererScale(double scale)
Sets the renderer map scale.
Qgis::RenderContextFlags flags() const
Returns combination of flags used for rendering.
const QgsPathResolver & pathResolver() const
Returns the path resolver for conversion between relative and absolute paths during rendering operati...
void renderPolygon(const QPolygonF &points, const QVector< QPolygonF > *rings, QgsSymbolRenderContext &context) override
Renders the fill symbol layer for the polygon whose outer ring is defined by points,...
void setParameters(const QMap< QString, QgsProperty > &parameters)
Sets the dynamic SVG parameters.
QString svgFilePath() const
Returns the path to the SVG file used to render the fill.
void startRender(QgsSymbolRenderContext &context) override
Called before a set of rendering operations commences on the supplied render context.
QColor dxfColor(QgsSymbolRenderContext &context) const override
Gets color.
bool setSubSymbol(QgsSymbol *symbol) override
Sets layer's subsymbol. takes ownership of the passed symbol.
QColor svgStrokeColor() const
Returns the stroke color used for rendering the SVG content.
bool usesMapUnits() const override
Returns true if the symbol layer has any components which use map unit based sizes.
void stopRender(QgsSymbolRenderContext &context) override
Called after a set of rendering operations has finished on the supplied render context.
Qgis::RenderUnit patternWidthUnit() const
Returns the units for the width of the SVG images in the pattern.
const QgsMapUnitScale & svgStrokeWidthMapUnitScale() const
Returns the map unit scale for the pattern's stroke.
double svgStrokeWidth() const
Returns the stroke width used for rendering the SVG content.
QString layerType() const override
Returns a string that represents this layer type.
void setOutputUnit(Qgis::RenderUnit unit) override
Sets the units to use for sizes and widths within the symbol layer.
QMap< QString, QgsProperty > parameters() const
Returns the dynamic SVG parameters.
QgsSVGFillSymbolLayer * clone() const override
Shall be reimplemented by subclasses to create a deep copy of the instance.
double estimateMaxBleed(const QgsRenderContext &context) const override
Returns the estimated maximum distance which the layer style will bleed outside the drawn shape when ...
QSet< QString > usedAttributes(const QgsRenderContext &context) const override
Returns the set of attributes referenced by the layer.
QgsSVGFillSymbolLayer(const QString &svgFilePath, double width=20, double rotation=0.0)
Constructor for QgsSVGFillSymbolLayer, using the SVG picture at the specified absolute file path.
void setSvgFilePath(const QString &svgPath)
Sets the path to the SVG file to render in the fill.
QColor svgFillColor() const
Returns the fill color used for rendering the SVG content.
static void resolvePaths(QVariantMap &properties, const QgsPathResolver &pathResolver, bool saving)
Turns relative paths in properties map to absolute when reading and vice versa when writing.
QVariantMap properties() const override
Should be reimplemented by subclasses to return a string map that contains the configuration informat...
const QgsMapUnitScale & patternWidthMapUnitScale() const
Returns the map unit scale for the pattern's width.
static std::unique_ptr< QgsSymbolLayer > createFromSld(QDomElement &element)
Creates a new QgsSVGFillSymbolLayer from a SLD element.
Qgis::RenderUnit svgStrokeWidthUnit() const
Returns the units for the stroke width.
double patternWidth() const
Returns the width of the rendered SVG content within the fill (i.e.
bool hasDataDefinedProperties() const override
Returns true if the symbol layer (or any of its sub-symbols) contains data defined properties.
~QgsSVGFillSymbolLayer() override
void setMapUnitScale(const QgsMapUnitScale &scale) override
Q_DECL_DEPRECATED void toSld(QDomDocument &doc, QDomElement &element, const QVariantMap &props) const override
Saves the symbol layer as SLD.
static std::unique_ptr< QgsSymbolLayer > create(const QVariantMap &properties=QVariantMap())
Creates a new QgsSVGFillSymbolLayer from a properties map.
void applyDataDefinedSettings(QgsSymbolRenderContext &context) override
Applies data defined settings prior to generating the fill symbol brush.
QgsMapUnitScale mapUnitScale() const override
Qgis::RenderUnit outputUnit() const override
Returns the units to use for sizes and widths within the symbol layer.
QgsSymbol * subSymbol() override
Returns the symbol's sub symbol, if present.
Scoped object for saving and restoring a QPainter object's state.
@ NoSave
Do not save the current painter state.
void startRender(QgsSymbolRenderContext &context) override
Called before a set of rendering operations commences on the supplied render context.
QgsShapeburstFillSymbolLayer(const QColor &color=DEFAULT_SIMPLEFILL_COLOR, const QColor &color2=Qt::white, Qgis::GradientColorSource colorType=Qgis::GradientColorSource::SimpleTwoColor, int blurRadius=0, bool useWholeShape=true, double maxDistance=5)
Constructor for QgsShapeburstFillSymbolLayer.
QgsShapeburstFillSymbolLayer * clone() const override
Shall be reimplemented by subclasses to create a deep copy of the instance.
~QgsShapeburstFillSymbolLayer() override
int blurRadius() const
Returns the blur radius, which controls the amount of blurring applied to the fill.
QVariantMap properties() const override
Should be reimplemented by subclasses to return a string map that contains the configuration informat...
bool usesMapUnits() const override
Returns true if the symbol layer has any components which use map unit based sizes.
void setOutputUnit(Qgis::RenderUnit unit) override
Sets the units to use for sizes and widths within the symbol layer.
void stopRender(QgsSymbolRenderContext &context) override
Called after a set of rendering operations has finished on the supplied render context.
QColor color2() const
Returns the color used for the endpoint of the shapeburst fill.
void setMapUnitScale(const QgsMapUnitScale &scale) override
QgsMapUnitScale mapUnitScale() const override
void renderPolygon(const QPolygonF &points, const QVector< QPolygonF > *rings, QgsSymbolRenderContext &context) override
Renders the fill symbol layer for the polygon whose outer ring is defined by points,...
bool canCauseArtifactsBetweenAdjacentTiles() const override
Returns true if the symbol layer rendering can cause visible artifacts across a single feature when t...
static std::unique_ptr< QgsSymbolLayer > create(const QVariantMap &properties=QVariantMap())
Creates a new QgsShapeburstFillSymbolLayer using the specified properties map containing symbol prope...
Qgis::RenderUnit outputUnit() const override
Returns the units to use for sizes and widths within the symbol layer.
QPointF offset() const
Returns the offset for the shapeburst fill.
bool useWholeShape() const
Returns whether the shapeburst fill is set to cover the entire shape.
bool ignoreRings() const
Returns whether the shapeburst fill is set to ignore polygon interior rings.
double maxDistance() const
Returns the maximum distance from the shape's boundary which is shaded.
Qgis::SymbolLayerFlags flags() const override
Returns flags which control the symbol layer's behavior.
QString layerType() const override
Returns a string that represents this layer type.
Qgis::GradientColorSource colorType() const
Returns the color mode used for the shapeburst fill.
double estimateMaxBleed(const QgsRenderContext &context) const override
Returns the estimated maximum distance which the layer style will bleed outside the drawn shape when ...
void setColorRamp(QgsColorRamp *ramp)
Sets the color ramp used to draw the shapeburst fill.
QgsSimpleFillSymbolLayer(const QColor &color=DEFAULT_SIMPLEFILL_COLOR, Qt::BrushStyle style=DEFAULT_SIMPLEFILL_STYLE, const QColor &strokeColor=DEFAULT_SIMPLEFILL_BORDERCOLOR, Qt::PenStyle strokeStyle=DEFAULT_SIMPLEFILL_BORDERSTYLE, double strokeWidth=DEFAULT_SIMPLEFILL_BORDERWIDTH, Qt::PenJoinStyle penJoinStyle=DEFAULT_SIMPLEFILL_JOINSTYLE)
Qt::PenJoinStyle penJoinStyle() const
QColor strokeColor() const override
Returns the stroke color for the symbol layer.
QColor dxfBrushColor(QgsSymbolRenderContext &context) const override
Gets brush/fill color.
bool usesMapUnits() const override
Returns true if the symbol layer has any components which use map unit based sizes.
Qt::BrushStyle dxfBrushStyle() const override
Gets brush/fill style.
QString ogrFeatureStyle(double mmScaleFactor, double mapUnitScaleFactor) const override
void startRender(QgsSymbolRenderContext &context) override
Called before a set of rendering operations commences on the supplied render context.
Qgis::SymbolLayerFlags flags() const override
Returns flags which control the symbol layer's behavior.
~QgsSimpleFillSymbolLayer() override
Q_DECL_DEPRECATED void toSld(QDomDocument &doc, QDomElement &element, const QVariantMap &props) const override
Saves the symbol layer as SLD.
double estimateMaxBleed(const QgsRenderContext &context) const override
Returns the estimated maximum distance which the layer style will bleed outside the drawn shape when ...
QColor dxfColor(QgsSymbolRenderContext &context) const override
Gets color.
QColor fillColor() const override
Returns the fill color for the symbol layer.
Qt::PenStyle strokeStyle() const
QString layerType() const override
Returns a string that represents this layer type.
double dxfAngle(QgsSymbolRenderContext &context) const override
Gets angle.
void setOutputUnit(Qgis::RenderUnit unit) override
Sets the units to use for sizes and widths within the symbol layer.
QgsMapUnitScale mOffsetMapUnitScale
Qgis::RenderUnit mStrokeWidthUnit
void stopRender(QgsSymbolRenderContext &context) override
Called after a set of rendering operations has finished on the supplied render context.
QPointF offset() const
Returns the offset by which polygons will be translated during rendering.
Qt::PenStyle dxfPenStyle() const override
Gets pen style.
QgsMapUnitScale mStrokeWidthMapUnitScale
static std::unique_ptr< QgsSymbolLayer > create(const QVariantMap &properties=QVariantMap())
Creates a new QgsSimpleFillSymbolLayer using the specified properties map containing symbol propertie...
QImage toTiledPatternImage() const override
Renders the symbol layer as an image that can be used as a seamless pattern fill for polygons,...
static std::unique_ptr< QgsSymbolLayer > createFromSld(QDomElement &element)
void renderPolygon(const QPolygonF &points, const QVector< QPolygonF > *rings, QgsSymbolRenderContext &context) override
Renders the fill symbol layer for the polygon whose outer ring is defined by points,...
QgsSimpleFillSymbolLayer * clone() const override
Shall be reimplemented by subclasses to create a deep copy of the instance.
double dxfWidth(QgsSymbolRenderContext &context) const override
Gets line width.
QgsMapUnitScale mapUnitScale() const override
Qgis::RenderUnit outputUnit() const override
Returns the units to use for sizes and widths within the symbol layer.
void setMapUnitScale(const QgsMapUnitScale &scale) override
QVariantMap properties() const override
Should be reimplemented by subclasses to return a string map that contains the configuration informat...
Holds SLD export options and other information related to SLD export of a QGIS layer style.
QString exportFilePath() const
Returns the export file path for the SLD.
void setExtraProperties(const QVariantMap &properties)
Sets the open ended set of properties that can drive/inform the SLD encoding.
void pushWarning(const QString &warning)
Pushes a warning message generated during the conversion.
Qgis::SldExportOptions exportOptions() const
Returns the export options.
QVariantMap extraProperties() const
Returns the open ended set of properties that can drive/inform the SLD encoding.
QByteArray getImageData(const QString &path, bool blocking=false) const
Gets the SVG content corresponding to the given path.
QPicture svgAsPicture(const QString &path, double size, const QColor &fill, const QColor &stroke, double strokeWidth, double widthScaleFactor, bool forceVectorOutput=false, double fixedAspectRatio=0, bool blocking=false, const QMap< QString, QString > &parameters=QMap< QString, QString >())
Returns an SVG drawing as a QPicture.
void containsParams(const QString &path, bool &hasFillParam, QColor &defaultFillColor, bool &hasStrokeParam, QColor &defaultStrokeColor, bool &hasStrokeWidthParam, double &defaultStrokeWidth, bool blocking=false) const
Tests if an SVG file contains parameters for fill, stroke color, stroke width.
QImage svgAsImage(const QString &path, double size, const QColor &fill, const QColor &stroke, double strokeWidth, double widthScaleFactor, bool &fitsInCache, double fixedAspectRatio=0, bool blocking=false, const QMap< QString, QString > &parameters=QMap< QString, QString >())
Returns an SVG drawing as a QImage.
static bool rotationFromSldElement(QDomElement &element, QString &rotationFunc)
static Qgis::MarkerClipMode decodeMarkerClipMode(const QString &string, bool *ok=nullptr)
Decodes a string representing a marker clip mode.
static QString encodePenStyle(Qt::PenStyle style)
static Qt::PenJoinStyle decodePenJoinStyle(const QString &str)
static QString encodeMapUnitScale(const QgsMapUnitScale &mapUnitScale)
static QgsStringMap evaluatePropertiesMap(const QMap< QString, QgsProperty > &propertiesMap, const QgsExpressionContext &context)
Evaluates a map of properties using the given context and returns a variant map with evaluated expres...
static bool displacementFromSldElement(QDomElement &element, QPointF &offset)
static QPointF polygonCentroid(const QPolygonF &points)
Calculate the centroid point of a QPolygonF.
static QString encodeBrushStyle(Qt::BrushStyle style)
static QString svgSymbolPathToName(const QString &path, const QgsPathResolver &pathResolver)
Determines an SVG symbol's name from its path.
static void externalGraphicToSld(QDomDocument &doc, QDomElement &element, const QString &path, const QString &mime, const QColor &color, double size=-1)
static QPointF polygonPointOnSurface(const QPolygonF &points, const QVector< QPolygonF > *rings=nullptr)
Calculate a point on the surface of a QPolygonF.
static QPointF toPoint(const QVariant &value, bool *ok=nullptr)
Converts a value to a point.
static void multiplyImageOpacity(QImage *image, qreal opacity)
Multiplies opacity of image pixel values with a (global) transparency value.
static QgsMapUnitScale decodeMapUnitScale(const QString &str)
static double rescaleUom(double size, Qgis::RenderUnit unit, const QVariantMap &props)
Rescales the given size based on the uomScale found in the props, if any is found,...
static std::unique_ptr< QgsSymbolLayer > createMarkerLayerFromSld(QDomElement &element)
Creates a new marker layer from a SLD DOM element.
static QString ogrFeatureStylePen(double width, double mmScaleFactor, double mapUnitsScaleFactor, const QColor &c, Qt::PenJoinStyle joinStyle=Qt::MiterJoin, Qt::PenCapStyle capStyle=Qt::FlatCap, double offset=0.0, const QVector< qreal > *dashPattern=nullptr)
Create ogr feature style string for pen.
static bool externalGraphicFromSld(QDomElement &element, QString &path, QString &mime, QColor &color, double &size)
static Q_DECL_DEPRECATED void parametricSvgToSld(QDomDocument &doc, QDomElement &graphicElem, const QString &path, const QColor &fillColor, double size, const QColor &strokeColor, double strokeWidth)
Encodes a reference to a parametric SVG into SLD, as a succession of parametric SVG using URL paramet...
static bool lineFromSld(QDomElement &element, Qt::PenStyle &penStyle, QColor &color, double &width, Qt::PenJoinStyle *penJoinStyle=nullptr, Qt::PenCapStyle *penCapStyle=nullptr, QVector< qreal > *customDashPattern=nullptr, double *dashOffset=nullptr)
static std::unique_ptr< QgsSymbolLayer > createLineLayerFromSld(QDomElement &element)
Creates a new line layer from a SLD DOM element.
static QString ogrFeatureStyleBrush(const QColor &fillColr)
Create ogr feature style string for brush.
static QString encodeLineClipMode(Qgis::LineClipMode mode)
Encodes a line clip mode to a string.
static Qgis::LineClipMode decodeLineClipMode(const QString &string, bool *ok=nullptr)
Decodes a string representing a line clip mode.
static QPointF pointOnLineWithDistance(QPointF startPoint, QPointF directionPoint, double distance)
Returns a point on the line from startPoint to directionPoint that is a certain distance away from th...
static QSize tileSize(int width, int height, double &angleRad)
Calculate the minimum size in pixels of a symbol tile given the symbol width and height and the symbo...
static Qt::BrushStyle decodeBrushStyle(const QString &str)
static QDomElement createVendorOptionElement(QDomDocument &doc, const QString &name, const QString &value)
static bool wellKnownMarkerFromSld(QDomElement &element, QString &name, QColor &color, QColor &strokeColor, Qt::PenStyle &strokeStyle, double &strokeWidth, double &size)
Extracts properties from an SLD marker definition.
static void createDisplacementElement(QDomDocument &doc, QDomElement &element, QPointF offset)
static QString svgSymbolNameToPath(const QString &name, const QgsPathResolver &pathResolver)
Determines an SVG symbol's path from its name.
static QString encodeColor(const QColor &color)
Lossy-encodes a color to a string.
static bool fillFromSld(QDomElement &element, Qt::BrushStyle &brushStyle, QColor &color)
static Q_DECL_DEPRECATED void fillToSld(QDomDocument &doc, QDomElement &element, Qt::BrushStyle brushStyle, const QColor &color=QColor())
Exports fill details to an SLD element.
static Qgis::RenderUnit decodeSldUom(const QString &str, double *scaleFactor=nullptr)
Decodes a SLD unit of measure string to a render unit.
static Q_DECL_DEPRECATED void createGeometryElement(QDomDocument &doc, QDomElement &element, const QString &geomFunc)
Creates an SLD geometry element.
static double estimateMaxSymbolBleed(QgsSymbol *symbol, const QgsRenderContext &context)
Returns the maximum estimated bleed for the symbol.
static Q_DECL_DEPRECATED void wellKnownMarkerToSld(QDomDocument &doc, QDomElement &element, const QString &name, const QColor &color, const QColor &strokeColor, Qt::PenStyle strokeStyle, double strokeWidth=-1, double size=-1)
Exports a marker to SLD.
static Qt::PenStyle decodePenStyle(const QString &str)
static Q_DECL_DEPRECATED void createRotationElement(QDomDocument &doc, QDomElement &element, const QString &rotationFunc)
Creates SLD rotation element.
static Qgis::SymbolCoordinateReference decodeCoordinateReference(const QString &string, bool *ok=nullptr)
Decodes a string representing a symbol coordinate reference mode.
static QString encodePoint(QPointF point)
Encodes a QPointF to a string.
static QString encodePenJoinStyle(Qt::PenJoinStyle style)
static QgsStringMap getVendorOptionList(QDomElement &element)
static QPointF decodePoint(const QString &string)
Decodes a QSizeF from a string.
static QString encodeCoordinateReference(Qgis::SymbolCoordinateReference coordinateReference)
Encodes a symbol coordinate reference mode to a string.
static QString encodeMarkerClipMode(Qgis::MarkerClipMode mode)
Encodes a marker clip mode to a string.
static void lineToSld(QDomDocument &doc, QDomElement &element, Qt::PenStyle penStyle, const QColor &color, QgsSldExportContext &context, double width=-1, const Qt::PenJoinStyle *penJoinStyle=nullptr, const Qt::PenCapStyle *penCapStyle=nullptr, const QVector< qreal > *customDashPattern=nullptr, double dashOffset=0.0)
void copyCommonProperties(QgsSymbolLayer *destLayer) const
Copies all common base class properties from this layer to another symbol layer.
virtual bool setSubSymbol(QgsSymbol *symbol)
Sets layer's subsymbol. takes ownership of the passed symbol.
bool shouldRenderUsingSelectionColor(const QgsSymbolRenderContext &context) const
Returns true if the symbol layer should be rendered using the selection color from the render context...
Qgis::SymbolType type() const
friend class QgsSymbol
virtual QColor fillColor() const
Returns the fill color for the symbol layer.
static const bool SELECTION_IS_OPAQUE
Whether styles for selected features ignore symbol alpha.
bool installMasks(QgsRenderContext &context, bool recursive, const QRectF &rect=QRectF())
When rendering, install masks on context painter.
void removeMasks(QgsRenderContext &context, bool recursive)
When rendering, remove previously installed masks from context painter if recursive is true masks are...
virtual QSet< QString > usedAttributes(const QgsRenderContext &context) const
Returns the set of attributes referenced by the layer.
@ GradientType
Gradient fill type.
@ SecondaryColor
Secondary color (eg for gradient fills).
@ File
Filename, eg for svg files.
@ GradientReference2Y
Gradient reference point 2 y.
@ GradientReference1X
Gradient reference point 1 x.
@ OffsetY
Vertical offset.
@ OffsetX
Horizontal offset.
@ GradientReference1Y
Gradient reference point 1 y.
@ GradientSpread
Gradient spread mode.
@ ShapeburstMaxDistance
Shapeburst fill from edge distance.
@ StrokeStyle
Stroke style (eg solid, dashed).
@ DistanceY
Vertical distance between points.
@ ClipPoints
Whether markers should be clipped to polygon boundaries.
@ LineClipping
Line clipping mode.
@ ShapeburstIgnoreRings
Shapeburst ignore rings.
@ ShapeburstUseWholeShape
Shapeburst use whole shape.
@ DisplacementX
Horizontal displacement.
@ CoordinateMode
Gradient coordinate mode.
@ FillStyle
Fill style (eg solid, dots).
@ GradientReference2X
Gradient reference point 2 x.
@ BlurRadius
Shapeburst blur radius.
@ MarkerClipping
Marker clipping mode.
@ RandomSeed
Random number seed.
@ LineAngle
Line angle, or angle of hash lines for hash line symbols.
@ JoinStyle
Line join style.
@ RandomOffsetY
Random offset Y.
@ DisplacementY
Vertical displacement.
@ DistanceX
Horizontal distance between points.
@ GradientReference1IsCentroid
Gradient reference point 1 is centroid.
@ GradientReference2IsCentroid
Gradient reference point 2 is centroid.
@ LineDistance
Distance between lines, or length of lines for hash line symbols.
@ RandomOffsetX
Random offset X.
void restoreOldDataDefinedProperties(const QVariantMap &stringMap)
Restores older data defined properties from string map.
virtual double estimateMaxBleed(const QgsRenderContext &context) const
Returns the estimated maximum distance which the layer style will bleed outside the drawn shape when ...
static const bool SELECT_FILL_BORDER
Whether fill styles for selected features also highlight symbol stroke.
virtual bool rendersIdenticallyTo(const QgsSymbolLayer *other) const
Returns true if this symbol layer will always render identically to an other symbol layer.
virtual QString layerType() const =0
Returns a string that represents this layer type.
virtual QColor color() const
Returns the "representative" color of the symbol layer.
virtual QColor strokeColor() const
Returns the stroke color for the symbol layer.
virtual Qgis::SymbolLayerFlags flags() const
Returns flags which control the symbol layer's behavior.
QgsPropertyCollection mDataDefinedProperties
QgsPropertyCollection & dataDefinedProperties()
Returns a reference to the symbol layer's property collection, used for data defined overrides.
static const bool SELECT_FILL_STYLE
Whether fill styles for selected features uses symbol layer style.
virtual bool hasDataDefinedProperties() const
Returns true if the symbol layer (or any of its sub-symbols) contains data defined properties.
QgsSymbolLayer(const QgsSymbolLayer &other)
Encapsulates the context in which a symbol is being rendered.
const QgsFeature * feature() const
Returns the current feature being rendered.
QgsFields fields() const
Fields of the layer.
void setOriginalValueVariable(const QVariant &value)
Sets the original value variable value for data defined symbology.
bool forceVectorRendering() const
Returns true if symbol must be rendered using vector methods, and optimisations like pre-rendered ima...
qreal opacity() const
Returns the opacity for the symbol.
QgsRenderContext & renderContext()
Returns a reference to the context's render context.
QColor color() const
Returns the symbol's color.
Qgis::SymbolType type() const
Returns the symbol's type.
Definition qgssymbol.h:296
double interval() const
Returns the interval between individual symbols.
const QgsMapUnitScale & intervalMapUnitScale() const
Returns the map unit scale for the interval between symbols.
void setInterval(double interval)
Sets the interval between individual symbols.
Qgis::RenderUnit intervalUnit() const
Returns the units for the interval between symbols.
static Q_INVOKABLE Qgis::RenderUnit decodeRenderUnit(const QString &string, bool *ok=nullptr)
Decodes a render unit from a string.
static Q_INVOKABLE QString encodeUnit(Qgis::DistanceUnit unit)
Encodes a distance unit to a string.
static bool isNull(const QVariant &variant, bool silenceNullWarnings=false)
Returns true if the specified variant should be considered a NULL value.
As part of the API refactoring and improvements which landed in the Processing API was substantially reworked from the x version This was done in order to allow much of the underlying Processing framework to be ported into c
QString qgsDoubleToString(double a, int precision=17)
Returns a string representation of a double.
Definition qgis.h:7718
bool qgsDoubleNear(double a, double b, double epsilon=4 *std::numeric_limits< double >::epsilon())
Compare two doubles (but allow some difference).
Definition qgis.h:7811
QMap< QString, QString > QgsStringMap
Definition qgis.h:8418
T qgsgeometry_cast(QgsAbstractGeometry *geom)
constexpr QgsDataDefinedStringDecoder< V, N > makeDataDefinedStringDecoder(const DataDefinedDecoderEntry< V >(&values)[N])
Creates a QgsDataDefinedStringDecoder from a hardcoded lookup table.
#define DEFAULT_SIMPLEFILL_JOINSTYLE
#define INF
#define DEFAULT_SIMPLEFILL_COLOR
#define DEFAULT_SIMPLEFILL_STYLE
#define DEFAULT_SIMPLEFILL_BORDERSTYLE
#define DEFAULT_SIMPLEFILL_BORDERCOLOR
#define DEFAULT_SIMPLEFILL_BORDERWIDTH
#define INF
#define QgsDebugError(str)
Definition qgslogger.h:71
QList< QgsSymbolLayer * > QgsSymbolLayerList
Definition qgssymbol.h:30
Single variable definition for use within a QgsExpressionContextScope.