QGIS API Documentation 3.41.0-Master (3440c17df1d)
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 "qgsfileutils.h"
17#include "qgsfillsymbollayer.h"
18#include "qgslinesymbollayer.h"
19#include "qgssldexportcontext.h"
20#include "qgssymbollayerutils.h"
21#include "qgsdxfexport.h"
22#include "qgsgeometry.h"
23#include "qgsimagecache.h"
24#include "qgsrendercontext.h"
25#include "qgsproject.h"
26#include "qgssvgcache.h"
27#include "qgscolorramp.h"
28#include "qgscolorrampimpl.h"
29#include "qgsunittypes.h"
30#include "qgsmessagelog.h"
31#include "qgsapplication.h"
32#include "qgsimageoperation.h"
33#include "qgspolygon.h"
34#include "qgslinestring.h"
36#include "qgssymbol.h"
37#include "qgsmarkersymbol.h"
38#include "qgslinesymbol.h"
39#include "qgsfeedback.h"
40#include "qgsgeometryengine.h"
41#include "qgscolorutils.h"
42
43#include <QPainter>
44#include <QPagedPaintDevice>
45#include <QFile>
46#include <QSvgRenderer>
47#include <QDomDocument>
48#include <QDomElement>
49#include <QtMath>
50#include <random>
51
52
53QgsSimpleFillSymbolLayer::QgsSimpleFillSymbolLayer( const QColor &color, Qt::BrushStyle style, const QColor &strokeColor, Qt::PenStyle strokeStyle, double strokeWidth,
54 Qt::PenJoinStyle penJoinStyle )
55 : mBrushStyle( style )
56 , mStrokeColor( strokeColor )
57 , mStrokeStyle( strokeStyle )
58 , mStrokeWidth( strokeWidth )
59 , mPenJoinStyle( penJoinStyle )
60{
61 mColor = color;
62}
63
65
71
73{
75 if ( mOffsetUnit != unit )
76 {
78 }
79 return unit;
80}
81
87
93
102
103void QgsSimpleFillSymbolLayer::applyDataDefinedSymbology( QgsSymbolRenderContext &context, QBrush &brush, QPen &pen, QPen &selPen )
104{
105 if ( !dataDefinedProperties().hasActiveProperties() )
106 return; // shortcut
107
108 bool ok;
109
111 {
114 fillColor.setAlphaF( context.opacity() * fillColor.alphaF() );
115 brush.setColor( fillColor );
116 }
118 {
121 if ( !QgsVariantUtils::isNull( exprVal ) )
122 brush.setStyle( QgsSymbolLayerUtils::decodeBrushStyle( exprVal.toString() ) );
123 }
125 {
128 penColor.setAlphaF( context.opacity() * penColor.alphaF() );
129 pen.setColor( penColor );
130 }
132 {
135 if ( !QgsVariantUtils::isNull( exprVal ) )
136 {
137 double width = exprVal.toDouble( &ok );
138 if ( ok )
139 {
141 pen.setWidthF( width );
142 selPen.setWidthF( width );
143 }
144 }
145 }
147 {
150 if ( ok )
151 {
152 pen.setStyle( QgsSymbolLayerUtils::decodePenStyle( style ) );
153 selPen.setStyle( QgsSymbolLayerUtils::decodePenStyle( style ) );
154 }
155 }
157 {
160 if ( ok )
161 {
162 pen.setJoinStyle( QgsSymbolLayerUtils::decodePenJoinStyle( style ) );
163 selPen.setJoinStyle( QgsSymbolLayerUtils::decodePenJoinStyle( style ) );
164 }
165 }
166}
167
168
170{
172 Qt::BrushStyle style = DEFAULT_SIMPLEFILL_STYLE;
177 QPointF offset;
178
179 if ( props.contains( QStringLiteral( "color" ) ) )
180 color = QgsColorUtils::colorFromString( props[QStringLiteral( "color" )].toString() );
181 if ( props.contains( QStringLiteral( "style" ) ) )
182 style = QgsSymbolLayerUtils::decodeBrushStyle( props[QStringLiteral( "style" )].toString() );
183 if ( props.contains( QStringLiteral( "color_border" ) ) )
184 {
185 //pre 2.5 projects used "color_border"
186 strokeColor = QgsColorUtils::colorFromString( props[QStringLiteral( "color_border" )].toString() );
187 }
188 else if ( props.contains( QStringLiteral( "outline_color" ) ) )
189 {
190 strokeColor = QgsColorUtils::colorFromString( props[QStringLiteral( "outline_color" )].toString() );
191 }
192 else if ( props.contains( QStringLiteral( "line_color" ) ) )
193 {
194 strokeColor = QgsColorUtils::colorFromString( props[QStringLiteral( "line_color" )].toString() );
195 }
196
197 if ( props.contains( QStringLiteral( "style_border" ) ) )
198 {
199 //pre 2.5 projects used "style_border"
200 strokeStyle = QgsSymbolLayerUtils::decodePenStyle( props[QStringLiteral( "style_border" )].toString() );
201 }
202 else if ( props.contains( QStringLiteral( "outline_style" ) ) )
203 {
204 strokeStyle = QgsSymbolLayerUtils::decodePenStyle( props[QStringLiteral( "outline_style" )].toString() );
205 }
206 else if ( props.contains( QStringLiteral( "line_style" ) ) )
207 {
208 strokeStyle = QgsSymbolLayerUtils::decodePenStyle( props[QStringLiteral( "line_style" )].toString() );
209 }
210 if ( props.contains( QStringLiteral( "width_border" ) ) )
211 {
212 //pre 2.5 projects used "width_border"
213 strokeWidth = props[QStringLiteral( "width_border" )].toDouble();
214 }
215 else if ( props.contains( QStringLiteral( "outline_width" ) ) )
216 {
217 strokeWidth = props[QStringLiteral( "outline_width" )].toDouble();
218 }
219 else if ( props.contains( QStringLiteral( "line_width" ) ) )
220 {
221 strokeWidth = props[QStringLiteral( "line_width" )].toDouble();
222 }
223 if ( props.contains( QStringLiteral( "offset" ) ) )
224 offset = QgsSymbolLayerUtils::decodePoint( props[QStringLiteral( "offset" )].toString() );
225 if ( props.contains( QStringLiteral( "joinstyle" ) ) )
226 penJoinStyle = QgsSymbolLayerUtils::decodePenJoinStyle( props[QStringLiteral( "joinstyle" )].toString() );
227
228 std::unique_ptr< QgsSimpleFillSymbolLayer > sl = std::make_unique< QgsSimpleFillSymbolLayer >( color, style, strokeColor, strokeStyle, strokeWidth, penJoinStyle );
229 sl->setOffset( offset );
230 if ( props.contains( QStringLiteral( "border_width_unit" ) ) )
231 {
232 sl->setStrokeWidthUnit( QgsUnitTypes::decodeRenderUnit( props[QStringLiteral( "border_width_unit" )].toString() ) );
233 }
234 else if ( props.contains( QStringLiteral( "outline_width_unit" ) ) )
235 {
236 sl->setStrokeWidthUnit( QgsUnitTypes::decodeRenderUnit( props[QStringLiteral( "outline_width_unit" )].toString() ) );
237 }
238 else if ( props.contains( QStringLiteral( "line_width_unit" ) ) )
239 {
240 sl->setStrokeWidthUnit( QgsUnitTypes::decodeRenderUnit( props[QStringLiteral( "line_width_unit" )].toString() ) );
241 }
242 if ( props.contains( QStringLiteral( "offset_unit" ) ) )
243 sl->setOffsetUnit( QgsUnitTypes::decodeRenderUnit( props[QStringLiteral( "offset_unit" )].toString() ) );
244
245 if ( props.contains( QStringLiteral( "border_width_map_unit_scale" ) ) )
246 sl->setStrokeWidthMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( props[QStringLiteral( "border_width_map_unit_scale" )].toString() ) );
247 if ( props.contains( QStringLiteral( "offset_map_unit_scale" ) ) )
248 sl->setOffsetMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( props[QStringLiteral( "offset_map_unit_scale" )].toString() ) );
249
250 sl->restoreOldDataDefinedProperties( props );
251
252 return sl.release();
253}
254
255
257{
258 return QStringLiteral( "SimpleFill" );
259}
260
265
267{
268 QColor fillColor = mColor;
269 fillColor.setAlphaF( context.opacity() * mColor.alphaF() );
270 mBrush = QBrush( fillColor, mBrushStyle );
271
272 QColor selColor = context.renderContext().selectionColor();
273 QColor selPenColor = selColor == mColor ? selColor : mStrokeColor;
274 if ( ! SELECTION_IS_OPAQUE )
275 selColor.setAlphaF( context.opacity() );
276 mSelBrush = QBrush( selColor );
277 // N.B. unless a "selection line color" is implemented in addition to the "selection color" option
278 // this would mean symbols with "no fill" look the same whether or not they are selected
279 if ( SELECT_FILL_STYLE )
280 mSelBrush.setStyle( mBrushStyle );
281
282 QColor strokeColor = mStrokeColor;
283 strokeColor.setAlphaF( context.opacity() * mStrokeColor.alphaF() );
284 mPen = QPen( strokeColor );
285 mSelPen = QPen( selPenColor );
286 mPen.setStyle( mStrokeStyle );
288 mPen.setJoinStyle( mPenJoinStyle );
289}
290
292{
293 Q_UNUSED( context )
294}
295
296void QgsSimpleFillSymbolLayer::renderPolygon( const QPolygonF &points, const QVector<QPolygonF> *rings, QgsSymbolRenderContext &context )
297{
298 QPainter *p = context.renderContext().painter();
299 if ( !p )
300 {
301 return;
302 }
303
304 QColor fillColor = mColor;
305 fillColor.setAlphaF( context.opacity() * mColor.alphaF() );
306 mBrush.setColor( fillColor );
307 QColor strokeColor = mStrokeColor;
308 strokeColor.setAlphaF( context.opacity() * mStrokeColor.alphaF() );
309 mPen.setColor( strokeColor );
310
311 applyDataDefinedSymbology( context, mBrush, mPen, mSelPen );
312
313 QPointF offset = mOffset;
314
316 {
319 bool ok = false;
320 const QPointF res = QgsSymbolLayerUtils::toPoint( val, &ok );
321 if ( ok )
322 offset = res;
323 }
324
325 if ( !offset.isNull() )
326 {
329 p->translate( offset );
330 }
331
332 const bool useSelectedColor = shouldRenderUsingSelectionColor( context );
333
334 if ( mBrush.style() == Qt::SolidPattern || mBrush.style() == Qt::NoBrush || !dynamic_cast<QPagedPaintDevice *>( p->device() ) )
335 {
336 p->setPen( useSelectedColor ? mSelPen : mPen );
337 p->setBrush( useSelectedColor ? mSelBrush : mBrush );
338 _renderPolygon( p, points, rings, context );
339 }
340 else
341 {
342 // workaround upstream issue https://github.com/qgis/QGIS/issues/36580
343 // when a non-solid brush is set with opacity, the opacity incorrectly applies to the pen
344 // when exporting to PDF/print devices
345 p->setBrush( useSelectedColor ? mSelBrush : mBrush );
346 p->setPen( Qt::NoPen );
347 _renderPolygon( p, points, rings, context );
348
349 p->setPen( useSelectedColor ? mSelPen : mPen );
350 p->setBrush( Qt::NoBrush );
351 _renderPolygon( p, points, rings, context );
352 }
353
354 if ( !offset.isNull() )
355 {
356 p->translate( -offset );
357 }
358}
359
361{
362 QVariantMap map;
363 map[QStringLiteral( "color" )] = QgsColorUtils::colorToString( mColor );
364 map[QStringLiteral( "style" )] = QgsSymbolLayerUtils::encodeBrushStyle( mBrushStyle );
365 map[QStringLiteral( "outline_color" )] = QgsColorUtils::colorToString( mStrokeColor );
366 map[QStringLiteral( "outline_style" )] = QgsSymbolLayerUtils::encodePenStyle( mStrokeStyle );
367 map[QStringLiteral( "outline_width" )] = QString::number( mStrokeWidth );
368 map[QStringLiteral( "outline_width_unit" )] = QgsUnitTypes::encodeUnit( mStrokeWidthUnit );
369 map[QStringLiteral( "border_width_map_unit_scale" )] = QgsSymbolLayerUtils::encodeMapUnitScale( mStrokeWidthMapUnitScale );
370 map[QStringLiteral( "joinstyle" )] = QgsSymbolLayerUtils::encodePenJoinStyle( mPenJoinStyle );
371 map[QStringLiteral( "offset" )] = QgsSymbolLayerUtils::encodePoint( mOffset );
372 map[QStringLiteral( "offset_unit" )] = QgsUnitTypes::encodeUnit( mOffsetUnit );
373 map[QStringLiteral( "offset_map_unit_scale" )] = QgsSymbolLayerUtils::encodeMapUnitScale( mOffsetMapUnitScale );
374 return map;
375}
376
378{
379 std::unique_ptr< QgsSimpleFillSymbolLayer > sl = std::make_unique< QgsSimpleFillSymbolLayer >( mColor, mBrushStyle, mStrokeColor, mStrokeStyle, mStrokeWidth, mPenJoinStyle );
380 sl->setOffset( mOffset );
381 sl->setOffsetUnit( mOffsetUnit );
382 sl->setOffsetMapUnitScale( mOffsetMapUnitScale );
383 sl->setStrokeWidthUnit( mStrokeWidthUnit );
384 sl->setStrokeWidthMapUnitScale( mStrokeWidthMapUnitScale );
385 copyDataDefinedProperties( sl.get() );
386 copyPaintEffect( sl.get() );
387 return sl.release();
388}
389
390void QgsSimpleFillSymbolLayer::toSld( QDomDocument &doc, QDomElement &element, const QVariantMap &props ) const
391{
392 if ( mBrushStyle == Qt::NoBrush && mStrokeStyle == Qt::NoPen )
393 return;
394
395 QDomElement symbolizerElem = doc.createElement( QStringLiteral( "se:PolygonSymbolizer" ) );
396 if ( !props.value( QStringLiteral( "uom" ), QString() ).toString().isEmpty() )
397 symbolizerElem.setAttribute( QStringLiteral( "uom" ), props.value( QStringLiteral( "uom" ), QString() ).toString() );
398 element.appendChild( symbolizerElem );
399
400 // <Geometry>
401 QgsSymbolLayerUtils::createGeometryElement( doc, symbolizerElem, props.value( QStringLiteral( "geom" ), QString() ).toString() );
402
403 const QgsSldExportContext context { props.value( QStringLiteral( "SldExportContext" ), QVariant::fromValue( QgsSldExportContext() ) ).value< QgsSldExportContext >() };
404
405
406 // Export to PNG
407 bool exportOk { false };
408 if ( ! context.exportFilePath().isEmpty() && context.exportOptions().testFlag( Qgis::SldExportOption::Png ) )
409 {
410 const QImage image { toTiledPatternImage( ) };
411 if ( ! image.isNull() )
412 {
413 // <Fill>
414 QDomElement fillElem = doc.createElement( QStringLiteral( "se:Fill" ) );
415 symbolizerElem.appendChild( fillElem );
416 QDomElement graphicFillElem = doc.createElement( QStringLiteral( "se:GraphicFill" ) );
417 fillElem.appendChild( graphicFillElem );
418 QDomElement graphicElem = doc.createElement( QStringLiteral( "se:Graphic" ) );
419 graphicFillElem.appendChild( graphicElem );
420 QgsRenderContext renderContext;
421 const QFileInfo info { context.exportFilePath() };
422 QString pngPath { info.completeSuffix().isEmpty() ? context.exportFilePath() : context.exportFilePath().chopped( info.completeSuffix().length() ).append( QStringLiteral( "png" ) ) };
423 pngPath = QgsFileUtils::uniquePath( pngPath );
424 image.save( pngPath );
425 QgsSymbolLayerUtils::externalGraphicToSld( doc, graphicElem, QFileInfo( pngPath ).fileName(), QStringLiteral( "image/png" ), QColor(), image.height() );
426 exportOk = true;
427 }
428 }
429
430 if ( ! exportOk )
431 {
432 if ( mBrushStyle != Qt::NoBrush )
433 {
434
435 QColor color { mColor };
436
437 // Apply alpha from symbol
438 bool ok;
439 const double alpha { props.value( QStringLiteral( "alpha" ), QVariant() ).toDouble( &ok ) };
440 if ( ok )
441 {
442 color.setAlphaF( color.alphaF() * alpha );
443 }
444 // <Fill>
445 QDomElement fillElem = doc.createElement( QStringLiteral( "se:Fill" ) );
446 symbolizerElem.appendChild( fillElem );
448 }
449
450 if ( mStrokeStyle != Qt::NoPen )
451 {
452 // <Stroke>
453 QDomElement strokeElem = doc.createElement( QStringLiteral( "se:Stroke" ) );
454 symbolizerElem.appendChild( strokeElem );
456 // Apply alpha from symbol
457 bool ok;
458 const double alpha { props.value( QStringLiteral( "alpha" ), QVariant() ).toDouble( &ok ) };
459 QColor strokeColor { mStrokeColor };
460 if ( ok )
461 {
462 strokeColor.setAlphaF( strokeColor.alphaF() * alpha );
463 }
465 }
466 }
467
468 // <se:Displacement>
471}
472
473QString QgsSimpleFillSymbolLayer::ogrFeatureStyle( double mmScaleFactor, double mapUnitScaleFactor ) const
474{
475 //brush
476 QString symbolStyle;
477 symbolStyle.append( QgsSymbolLayerUtils::ogrFeatureStyleBrush( mColor ) );
478 symbolStyle.append( ';' );
479 //pen
480 symbolStyle.append( QgsSymbolLayerUtils::ogrFeatureStylePen( mStrokeWidth, mmScaleFactor, mapUnitScaleFactor, mStrokeColor, mPenJoinStyle ) );
481 return symbolStyle;
482}
483
485{
486 QColor color, strokeColor;
487 Qt::BrushStyle fillStyle;
488 Qt::PenStyle strokeStyle;
489 double strokeWidth;
490
491 QDomElement fillElem = element.firstChildElement( QStringLiteral( "Fill" ) );
492 QgsSymbolLayerUtils::fillFromSld( fillElem, fillStyle, color );
493
494 QDomElement strokeElem = element.firstChildElement( QStringLiteral( "Stroke" ) );
496
497 QPointF offset;
499
500 double scaleFactor = 1.0;
501 const QString uom = element.attribute( QStringLiteral( "uom" ) );
502 Qgis::RenderUnit sldUnitSize = QgsSymbolLayerUtils::decodeSldUom( uom, &scaleFactor );
503 offset.setX( offset.x() * scaleFactor );
504 offset.setY( offset.y() * scaleFactor );
505 strokeWidth = strokeWidth * scaleFactor;
506
507 std::unique_ptr< QgsSimpleFillSymbolLayer > sl = std::make_unique< QgsSimpleFillSymbolLayer >( color, fillStyle, strokeColor, strokeStyle, strokeWidth );
508 sl->setOutputUnit( sldUnitSize );
509 sl->setOffset( offset );
510 return sl.release();
511}
512
514{
515 double penBleed = context.convertToPainterUnits( mStrokeStyle == Qt::NoPen ? 0 : ( mStrokeWidth / 2.0 ), mStrokeWidthUnit, mStrokeWidthMapUnitScale );
516 double offsetBleed = context.convertToPainterUnits( std::max( std::fabs( mOffset.x() ), std::fabs( mOffset.y() ) ), mOffsetUnit, mOffsetMapUnitScale );
517 return penBleed + offsetBleed;
518}
519
530
541
552
554{
555 return mStrokeStyle;
556}
557
567
569{
570 return mBrushStyle;
571}
572
574{
575 QPixmap pixmap( QSize( 32, 32 ) );
576 pixmap.fill( Qt::transparent );
577 QPainter painter;
578 painter.begin( &pixmap );
579 painter.setRenderHint( QPainter::Antialiasing );
580 QgsRenderContext renderContext = QgsRenderContext::fromQPainter( &painter );
584 renderContext.setForceVectorOutput( true );
585 QgsSymbolRenderContext symbolContext( renderContext, Qgis::RenderUnit::Pixels, 1.0, false, Qgis::SymbolRenderHints() );
586
587 std::unique_ptr< QgsSimpleFillSymbolLayer > layerClone( clone() );
588 layerClone->setStrokeStyle( Qt::PenStyle::NoPen );
589 layerClone->drawPreviewIcon( symbolContext, pixmap.size() );
590 painter.end();
591 return pixmap.toImage();
592}
593
594//QgsGradientFillSymbolLayer
595
596QgsGradientFillSymbolLayer::QgsGradientFillSymbolLayer( const QColor &color, const QColor &color2,
597 Qgis::GradientColorSource colorType, Qgis::GradientType gradientType,
599 : mGradientColorType( colorType )
600 , mGradientType( gradientType )
601 , mCoordinateMode( coordinateMode )
602 , mGradientSpread( spread )
603 , mReferencePoint1( QPointF( 0.5, 0 ) )
604 , mReferencePoint2( QPointF( 0.5, 1 ) )
605{
606 mColor = color;
607 mColor2 = color2;
608}
609
614
616{
617 //default to a two-color, linear gradient with feature mode and pad spreading
622 //default to gradient from the default fill color to white
623 QColor color = DEFAULT_SIMPLEFILL_COLOR, color2 = Qt::white;
624 QPointF referencePoint1 = QPointF( 0.5, 0 );
625 bool refPoint1IsCentroid = false;
626 QPointF referencePoint2 = QPointF( 0.5, 1 );
627 bool refPoint2IsCentroid = false;
628 double angle = 0;
629 QPointF offset;
630
631 //update gradient properties from props
632 if ( props.contains( QStringLiteral( "type" ) ) )
633 type = static_cast< Qgis::GradientType >( props[QStringLiteral( "type" )].toInt() );
634 if ( props.contains( QStringLiteral( "coordinate_mode" ) ) )
635 coordinateMode = static_cast< Qgis::SymbolCoordinateReference >( props[QStringLiteral( "coordinate_mode" )].toInt() );
636 if ( props.contains( QStringLiteral( "spread" ) ) )
637 gradientSpread = static_cast< Qgis::GradientSpread >( props[QStringLiteral( "spread" )].toInt() );
638 if ( props.contains( QStringLiteral( "color_type" ) ) )
639 colorType = static_cast< Qgis::GradientColorSource >( props[QStringLiteral( "color_type" )].toInt() );
640 if ( props.contains( QStringLiteral( "gradient_color" ) ) )
641 {
642 //pre 2.5 projects used "gradient_color"
643 color = QgsColorUtils::colorFromString( props[QStringLiteral( "gradient_color" )].toString() );
644 }
645 else if ( props.contains( QStringLiteral( "color" ) ) )
646 {
647 color = QgsColorUtils::colorFromString( props[QStringLiteral( "color" )].toString() );
648 }
649 if ( props.contains( QStringLiteral( "gradient_color2" ) ) )
650 {
651 color2 = QgsColorUtils::colorFromString( props[QStringLiteral( "gradient_color2" )].toString() );
652 }
653
654 if ( props.contains( QStringLiteral( "reference_point1" ) ) )
655 referencePoint1 = QgsSymbolLayerUtils::decodePoint( props[QStringLiteral( "reference_point1" )].toString() );
656 if ( props.contains( QStringLiteral( "reference_point1_iscentroid" ) ) )
657 refPoint1IsCentroid = props[QStringLiteral( "reference_point1_iscentroid" )].toInt();
658 if ( props.contains( QStringLiteral( "reference_point2" ) ) )
659 referencePoint2 = QgsSymbolLayerUtils::decodePoint( props[QStringLiteral( "reference_point2" )].toString() );
660 if ( props.contains( QStringLiteral( "reference_point2_iscentroid" ) ) )
661 refPoint2IsCentroid = props[QStringLiteral( "reference_point2_iscentroid" )].toInt();
662 if ( props.contains( QStringLiteral( "angle" ) ) )
663 angle = props[QStringLiteral( "angle" )].toDouble();
664
665 if ( props.contains( QStringLiteral( "offset" ) ) )
666 offset = QgsSymbolLayerUtils::decodePoint( props[QStringLiteral( "offset" )].toString() );
667
668 //attempt to create color ramp from props
669 QgsColorRamp *gradientRamp = nullptr;
670 if ( props.contains( QStringLiteral( "rampType" ) ) && props[QStringLiteral( "rampType" )] == QgsCptCityColorRamp::typeString() )
671 {
672 gradientRamp = QgsCptCityColorRamp::create( props );
673 }
674 else
675 {
676 gradientRamp = QgsGradientColorRamp::create( props );
677 }
678
679 //create a new gradient fill layer with desired properties
680 std::unique_ptr< QgsGradientFillSymbolLayer > sl = std::make_unique< QgsGradientFillSymbolLayer >( color, color2, colorType, type, coordinateMode, gradientSpread );
681 sl->setOffset( offset );
682 if ( props.contains( QStringLiteral( "offset_unit" ) ) )
683 sl->setOffsetUnit( QgsUnitTypes::decodeRenderUnit( props[QStringLiteral( "offset_unit" )].toString() ) );
684 if ( props.contains( QStringLiteral( "offset_map_unit_scale" ) ) )
685 sl->setOffsetMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( props[QStringLiteral( "offset_map_unit_scale" )].toString() ) );
686 sl->setReferencePoint1( referencePoint1 );
687 sl->setReferencePoint1IsCentroid( refPoint1IsCentroid );
688 sl->setReferencePoint2( referencePoint2 );
689 sl->setReferencePoint2IsCentroid( refPoint2IsCentroid );
690 sl->setAngle( angle );
691 if ( gradientRamp )
692 sl->setColorRamp( gradientRamp );
693
694 sl->restoreOldDataDefinedProperties( props );
695
696 return sl.release();
697}
698
703
709
711{
712 return QStringLiteral( "GradientFill" );
713}
714
715void QgsGradientFillSymbolLayer::applyDataDefinedSymbology( QgsSymbolRenderContext &context, const QPolygonF &points )
716{
718 {
719 //shortcut
722 return;
723 }
724
725 bool ok;
726
727 //first gradient color
728 QColor color = mColor;
730 {
733 color.setAlphaF( context.opacity() * color.alphaF() );
734 }
735
736 //second gradient color
737 QColor color2 = mColor2;
739 {
742 color2.setAlphaF( context.opacity() * color2.alphaF() );
743 }
744
745 //gradient rotation angle
746 double angle = mAngle;
748 {
751 }
752
753 //gradient type
756 {
758 if ( ok )
759 {
760 if ( currentType == QObject::tr( "linear" ) )
761 {
763 }
764 else if ( currentType == QObject::tr( "radial" ) )
765 {
767 }
768 else if ( currentType == QObject::tr( "conical" ) )
769 {
771 }
772 }
773 }
774
775 //coordinate mode
778 {
780 if ( ok )
781 {
782 if ( currentCoordMode == QObject::tr( "feature" ) )
783 {
785 }
786 else if ( currentCoordMode == QObject::tr( "viewport" ) )
787 {
789 }
790 }
791 }
792
793 //gradient spread
796 {
798 if ( ok )
799 {
800 if ( currentSpread == QObject::tr( "pad" ) )
801 {
803 }
804 else if ( currentSpread == QObject::tr( "repeat" ) )
805 {
807 }
808 else if ( currentSpread == QObject::tr( "reflect" ) )
809 {
811 }
812 }
813 }
814
815 //reference point 1 x & y
816 double refPoint1X = mReferencePoint1.x();
818 {
819 context.setOriginalValueVariable( refPoint1X );
821 }
822 double refPoint1Y = mReferencePoint1.y();
824 {
825 context.setOriginalValueVariable( refPoint1Y );
827 }
828 bool refPoint1IsCentroid = mReferencePoint1IsCentroid;
830 {
831 context.setOriginalValueVariable( refPoint1IsCentroid );
833 }
834
835 //reference point 2 x & y
836 double refPoint2X = mReferencePoint2.x();
838 {
839 context.setOriginalValueVariable( refPoint2X );
841 }
842 double refPoint2Y = mReferencePoint2.y();
844 {
845 context.setOriginalValueVariable( refPoint2Y );
847 }
848 bool refPoint2IsCentroid = mReferencePoint2IsCentroid;
850 {
851 context.setOriginalValueVariable( refPoint2IsCentroid );
853 }
854
855 if ( refPoint1IsCentroid || refPoint2IsCentroid )
856 {
857 //either the gradient is starting or ending at a centroid, so calculate it
858 QPointF centroid = QgsSymbolLayerUtils::polygonCentroid( points );
859 //centroid coordinates need to be scaled to a range [0, 1] relative to polygon bounds
860 QRectF bbox = points.boundingRect();
861 double centroidX = ( centroid.x() - bbox.left() ) / bbox.width();
862 double centroidY = ( centroid.y() - bbox.top() ) / bbox.height();
863
864 if ( refPoint1IsCentroid )
865 {
866 refPoint1X = centroidX;
867 refPoint1Y = centroidY;
868 }
869 if ( refPoint2IsCentroid )
870 {
871 refPoint2X = centroidX;
872 refPoint2Y = centroidY;
873 }
874 }
875
876 //update gradient with data defined values
878 spread, QPointF( refPoint1X, refPoint1Y ), QPointF( refPoint2X, refPoint2Y ), angle );
879}
880
881QPointF QgsGradientFillSymbolLayer::rotateReferencePoint( QPointF refPoint, double angle )
882{
883 //rotate a reference point by a specified angle around the point (0.5, 0.5)
884
885 //create a line from the centrepoint of a rectangle bounded by (0, 0) and (1, 1) to the reference point
886 QLineF refLine = QLineF( QPointF( 0.5, 0.5 ), refPoint );
887 //rotate this line by the current rotation angle
888 refLine.setAngle( refLine.angle() + angle );
889 //get new end point of line
890 QPointF rotatedReferencePoint = refLine.p2();
891 //make sure coords of new end point is within [0, 1]
892 if ( rotatedReferencePoint.x() > 1 )
893 rotatedReferencePoint.setX( 1 );
894 if ( rotatedReferencePoint.x() < 0 )
895 rotatedReferencePoint.setX( 0 );
896 if ( rotatedReferencePoint.y() > 1 )
897 rotatedReferencePoint.setY( 1 );
898 if ( rotatedReferencePoint.y() < 0 )
899 rotatedReferencePoint.setY( 0 );
900
901 return rotatedReferencePoint;
902}
903
904void QgsGradientFillSymbolLayer::applyGradient( const QgsSymbolRenderContext &context, QBrush &brush,
905 const QColor &color, const QColor &color2, Qgis::GradientColorSource gradientColorType,
906 QgsColorRamp *gradientRamp, Qgis::GradientType gradientType,
907 Qgis::SymbolCoordinateReference coordinateMode, Qgis::GradientSpread gradientSpread,
908 QPointF referencePoint1, QPointF referencePoint2, const double angle )
909{
910 //update alpha of gradient colors
911 QColor fillColor = color;
912 fillColor.setAlphaF( context.opacity() * fillColor.alphaF() );
913 QColor fillColor2 = color2;
914 fillColor2.setAlphaF( context.opacity() * fillColor2.alphaF() );
915
916 //rotate reference points
917 QPointF rotatedReferencePoint1 = !qgsDoubleNear( angle, 0.0 ) ? rotateReferencePoint( referencePoint1, angle ) : referencePoint1;
918 QPointF rotatedReferencePoint2 = !qgsDoubleNear( angle, 0.0 ) ? rotateReferencePoint( referencePoint2, angle ) : referencePoint2;
919
920 //create a QGradient with the desired properties
921 QGradient gradient;
922 switch ( gradientType )
923 {
925 gradient = QLinearGradient( rotatedReferencePoint1, rotatedReferencePoint2 );
926 break;
928 gradient = QRadialGradient( rotatedReferencePoint1, QLineF( rotatedReferencePoint1, rotatedReferencePoint2 ).length() );
929 break;
931 gradient = QConicalGradient( rotatedReferencePoint1, QLineF( rotatedReferencePoint1, rotatedReferencePoint2 ).angle() );
932 break;
933 }
934 switch ( coordinateMode )
935 {
937 gradient.setCoordinateMode( QGradient::ObjectBoundingMode );
938 break;
940 gradient.setCoordinateMode( QGradient::StretchToDeviceMode );
941 break;
942 }
943 switch ( gradientSpread )
944 {
946 gradient.setSpread( QGradient::PadSpread );
947 break;
949 gradient.setSpread( QGradient::ReflectSpread );
950 break;
952 gradient.setSpread( QGradient::RepeatSpread );
953 break;
954 }
955
956 //add stops to gradient
958 ( gradientRamp->type() == QgsGradientColorRamp::typeString() || gradientRamp->type() == QgsCptCityColorRamp::typeString() ) )
959 {
960 //color ramp gradient
961 QgsGradientColorRamp *gradRamp = static_cast<QgsGradientColorRamp *>( gradientRamp );
962 gradRamp->addStopsToGradient( &gradient, context.opacity() );
963 }
964 else
965 {
966 //two color gradient
967 gradient.setColorAt( 0.0, fillColor );
968 gradient.setColorAt( 1.0, fillColor2 );
969 }
970
971 //update QBrush use gradient
972 brush = QBrush( gradient );
973}
974
976{
977 QColor selColor = context.renderContext().selectionColor();
978 if ( ! SELECTION_IS_OPAQUE )
979 selColor.setAlphaF( context.opacity() );
980 mSelBrush = QBrush( selColor );
981}
982
984{
985 Q_UNUSED( context )
986}
987
988void QgsGradientFillSymbolLayer::renderPolygon( const QPolygonF &points, const QVector<QPolygonF> *rings, QgsSymbolRenderContext &context )
989{
990 QPainter *p = context.renderContext().painter();
991 if ( !p )
992 {
993 return;
994 }
995
996 applyDataDefinedSymbology( context, points );
997
998 const bool useSelectedColor = shouldRenderUsingSelectionColor( context );
999 p->setBrush( useSelectedColor ? mSelBrush : mBrush );
1000 p->setPen( Qt::NoPen );
1001
1002 QPointF offset = mOffset;
1004 {
1007 bool ok = false;
1008 const QPointF res = QgsSymbolLayerUtils::toPoint( val, &ok );
1009 if ( ok )
1010 offset = res;
1011 }
1012
1013 if ( !offset.isNull() )
1014 {
1017 p->translate( offset );
1018 }
1019
1020 _renderPolygon( p, points, rings, context );
1021
1022 if ( !offset.isNull() )
1023 {
1024 p->translate( -offset );
1025 }
1026}
1027
1029{
1030 QVariantMap map;
1031 map[QStringLiteral( "color" )] = QgsColorUtils::colorToString( mColor );
1032 map[QStringLiteral( "gradient_color2" )] = QgsColorUtils::colorToString( mColor2 );
1033 map[QStringLiteral( "color_type" )] = QString::number( static_cast< int >( mGradientColorType ) );
1034 map[QStringLiteral( "type" )] = QString::number( static_cast<int>( mGradientType ) );
1035 map[QStringLiteral( "coordinate_mode" )] = QString::number( static_cast< int >( mCoordinateMode ) );
1036 map[QStringLiteral( "spread" )] = QString::number( static_cast< int >( mGradientSpread ) );
1037 map[QStringLiteral( "reference_point1" )] = QgsSymbolLayerUtils::encodePoint( mReferencePoint1 );
1038 map[QStringLiteral( "reference_point1_iscentroid" )] = QString::number( mReferencePoint1IsCentroid );
1039 map[QStringLiteral( "reference_point2" )] = QgsSymbolLayerUtils::encodePoint( mReferencePoint2 );
1040 map[QStringLiteral( "reference_point2_iscentroid" )] = QString::number( mReferencePoint2IsCentroid );
1041 map[QStringLiteral( "angle" )] = QString::number( mAngle );
1042 map[QStringLiteral( "offset" )] = QgsSymbolLayerUtils::encodePoint( mOffset );
1043 map[QStringLiteral( "offset_unit" )] = QgsUnitTypes::encodeUnit( mOffsetUnit );
1044 map[QStringLiteral( "offset_map_unit_scale" )] = QgsSymbolLayerUtils::encodeMapUnitScale( mOffsetMapUnitScale );
1045 if ( mGradientRamp )
1046 {
1047 map.insert( mGradientRamp->properties() );
1048 }
1049 return map;
1050}
1051
1053{
1054 std::unique_ptr< QgsGradientFillSymbolLayer > sl = std::make_unique< QgsGradientFillSymbolLayer >( mColor, mColor2, mGradientColorType, mGradientType, mCoordinateMode, mGradientSpread );
1055 if ( mGradientRamp )
1056 sl->setColorRamp( mGradientRamp->clone() );
1057 sl->setReferencePoint1( mReferencePoint1 );
1058 sl->setReferencePoint1IsCentroid( mReferencePoint1IsCentroid );
1059 sl->setReferencePoint2( mReferencePoint2 );
1060 sl->setReferencePoint2IsCentroid( mReferencePoint2IsCentroid );
1061 sl->setAngle( mAngle );
1062 sl->setOffset( mOffset );
1063 sl->setOffsetUnit( mOffsetUnit );
1064 sl->setOffsetMapUnitScale( mOffsetMapUnitScale );
1065 copyDataDefinedProperties( sl.get() );
1066 copyPaintEffect( sl.get() );
1067 return sl.release();
1068}
1069
1071{
1072 double offsetBleed = context.convertToPainterUnits( std::max( std::fabs( mOffset.x() ), std::fabs( mOffset.y() ) ), mOffsetUnit, mOffsetMapUnitScale );
1073 return offsetBleed;
1074}
1075
1080
1085
1090
1095
1100
1105
1106//QgsShapeburstFillSymbolLayer
1107
1109 int blurRadius, bool useWholeShape, double maxDistance )
1110 : mBlurRadius( blurRadius )
1111 , mUseWholeShape( useWholeShape )
1112 , mMaxDistance( maxDistance )
1113 , mColorType( colorType )
1114 , mColor2( color2 )
1115{
1116 mColor = color;
1117}
1118
1120
1122{
1123 //default to a two-color gradient
1125 QColor color = DEFAULT_SIMPLEFILL_COLOR, color2 = Qt::white;
1126 int blurRadius = 0;
1127 bool useWholeShape = true;
1128 double maxDistance = 5;
1129 QPointF offset;
1130
1131 //update fill properties from props
1132 if ( props.contains( QStringLiteral( "color_type" ) ) )
1133 {
1134 colorType = static_cast< Qgis::GradientColorSource >( props[QStringLiteral( "color_type" )].toInt() );
1135 }
1136 if ( props.contains( QStringLiteral( "shapeburst_color" ) ) )
1137 {
1138 //pre 2.5 projects used "shapeburst_color"
1139 color = QgsColorUtils::colorFromString( props[QStringLiteral( "shapeburst_color" )].toString() );
1140 }
1141 else if ( props.contains( QStringLiteral( "color" ) ) )
1142 {
1143 color = QgsColorUtils::colorFromString( props[QStringLiteral( "color" )].toString() );
1144 }
1145
1146 if ( props.contains( QStringLiteral( "shapeburst_color2" ) ) )
1147 {
1148 //pre 2.5 projects used "shapeburst_color2"
1149 color2 = QgsColorUtils::colorFromString( props[QStringLiteral( "shapeburst_color2" )].toString() );
1150 }
1151 else if ( props.contains( QStringLiteral( "gradient_color2" ) ) )
1152 {
1153 color2 = QgsColorUtils::colorFromString( props[QStringLiteral( "gradient_color2" )].toString() );
1154 }
1155 if ( props.contains( QStringLiteral( "blur_radius" ) ) )
1156 {
1157 blurRadius = props[QStringLiteral( "blur_radius" )].toInt();
1158 }
1159 if ( props.contains( QStringLiteral( "use_whole_shape" ) ) )
1160 {
1161 useWholeShape = props[QStringLiteral( "use_whole_shape" )].toInt();
1162 }
1163 if ( props.contains( QStringLiteral( "max_distance" ) ) )
1164 {
1165 maxDistance = props[QStringLiteral( "max_distance" )].toDouble();
1166 }
1167 if ( props.contains( QStringLiteral( "offset" ) ) )
1168 {
1169 offset = QgsSymbolLayerUtils::decodePoint( props[QStringLiteral( "offset" )].toString() );
1170 }
1171
1172 //attempt to create color ramp from props
1173 QgsColorRamp *gradientRamp = nullptr;
1174 if ( props.contains( QStringLiteral( "rampType" ) ) && props[QStringLiteral( "rampType" )] == QgsCptCityColorRamp::typeString() )
1175 {
1176 gradientRamp = QgsCptCityColorRamp::create( props );
1177 }
1178 else
1179 {
1180 gradientRamp = QgsGradientColorRamp::create( props );
1181 }
1182
1183 //create a new shapeburst fill layer with desired properties
1184 std::unique_ptr< QgsShapeburstFillSymbolLayer > sl = std::make_unique< QgsShapeburstFillSymbolLayer >( color, color2, colorType, blurRadius, useWholeShape, maxDistance );
1185 sl->setOffset( offset );
1186 if ( props.contains( QStringLiteral( "offset_unit" ) ) )
1187 {
1188 sl->setOffsetUnit( QgsUnitTypes::decodeRenderUnit( props[QStringLiteral( "offset_unit" )].toString() ) );
1189 }
1190 if ( props.contains( QStringLiteral( "distance_unit" ) ) )
1191 {
1192 sl->setDistanceUnit( QgsUnitTypes::decodeRenderUnit( props[QStringLiteral( "distance_unit" )].toString() ) );
1193 }
1194 if ( props.contains( QStringLiteral( "offset_map_unit_scale" ) ) )
1195 {
1196 sl->setOffsetMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( props[QStringLiteral( "offset_map_unit_scale" )].toString() ) );
1197 }
1198 if ( props.contains( QStringLiteral( "distance_map_unit_scale" ) ) )
1199 {
1200 sl->setDistanceMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( props[QStringLiteral( "distance_map_unit_scale" )].toString() ) );
1201 }
1202 if ( props.contains( QStringLiteral( "ignore_rings" ) ) )
1203 {
1204 sl->setIgnoreRings( props[QStringLiteral( "ignore_rings" )].toInt() );
1205 }
1206 if ( gradientRamp )
1207 {
1208 sl->setColorRamp( gradientRamp );
1209 }
1210
1211 sl->restoreOldDataDefinedProperties( props );
1212
1213 return sl.release();
1214}
1215
1217{
1218 return QStringLiteral( "ShapeburstFill" );
1219}
1220
1225
1227{
1228 if ( mGradientRamp.get() == ramp )
1229 return;
1230
1231 mGradientRamp.reset( ramp );
1232}
1233
1234void QgsShapeburstFillSymbolLayer::applyDataDefinedSymbology( QgsSymbolRenderContext &context, QColor &color, QColor &color2, int &blurRadius, bool &useWholeShape,
1235 double &maxDistance, bool &ignoreRings )
1236{
1237 //first gradient color
1238 color = mColor;
1240 {
1243 }
1244
1245 //second gradient color
1246 color2 = mColor2;
1248 {
1251 }
1252
1253 //blur radius
1254 blurRadius = mBlurRadius;
1256 {
1257 context.setOriginalValueVariable( mBlurRadius );
1259 }
1260
1261 //use whole shape
1262 useWholeShape = mUseWholeShape;
1264 {
1265 context.setOriginalValueVariable( mUseWholeShape );
1267 }
1268
1269 //max distance
1270 maxDistance = mMaxDistance;
1272 {
1273 context.setOriginalValueVariable( mMaxDistance );
1275 }
1276
1277 //ignore rings
1278 ignoreRings = mIgnoreRings;
1280 {
1281 context.setOriginalValueVariable( mIgnoreRings );
1283 }
1284
1285}
1286
1288{
1289 //TODO - check this
1290 QColor selColor = context.renderContext().selectionColor();
1291 if ( ! SELECTION_IS_OPAQUE )
1292 selColor.setAlphaF( context.opacity() );
1293 mSelBrush = QBrush( selColor );
1294}
1295
1297{
1298 Q_UNUSED( context )
1299}
1300
1301void QgsShapeburstFillSymbolLayer::renderPolygon( const QPolygonF &points, const QVector<QPolygonF> *rings, QgsSymbolRenderContext &context )
1302{
1303 QPainter *p = context.renderContext().painter();
1304 if ( !p )
1305 {
1306 return;
1307 }
1308
1309 const bool useSelectedColor = shouldRenderUsingSelectionColor( context );
1310 if ( useSelectedColor )
1311 {
1312 //feature is selected, draw using selection style
1313 p->setBrush( mSelBrush );
1314 QPointF offset = mOffset;
1315
1317 {
1320 bool ok = false;
1321 const QPointF res = QgsSymbolLayerUtils::toPoint( val, &ok );
1322 if ( ok )
1323 offset = res;
1324 }
1325
1326 if ( !offset.isNull() )
1327 {
1328 offset.setX( context.renderContext().convertToPainterUnits( offset.x(), mOffsetUnit, mOffsetMapUnitScale ) );
1329 offset.setY( context.renderContext().convertToPainterUnits( offset.y(), mOffsetUnit, mOffsetMapUnitScale ) );
1330 p->translate( offset );
1331 }
1332 _renderPolygon( p, points, rings, context );
1333 if ( !offset.isNull() )
1334 {
1335 p->translate( -offset );
1336 }
1337 return;
1338 }
1339
1340 QColor color1, color2;
1341 int blurRadius;
1342 bool useWholeShape;
1343 double maxDistance;
1344 bool ignoreRings;
1345 //calculate data defined symbology
1346 applyDataDefinedSymbology( context, color1, color2, blurRadius, useWholeShape, maxDistance, ignoreRings );
1347
1348 //calculate max distance for shapeburst fill to extend from polygon boundary, in pixels
1349 int outputPixelMaxDist = 0;
1350 if ( !useWholeShape && !qgsDoubleNear( maxDistance, 0.0 ) )
1351 {
1352 //convert max distance to pixels
1353 outputPixelMaxDist = static_cast< int >( std::round( context.renderContext().convertToPainterUnits( maxDistance, mDistanceUnit, mDistanceMapUnitScale ) ) );
1354 }
1355
1356 //if we are using the two color mode, create a gradient ramp
1357 std::unique_ptr< QgsGradientColorRamp > twoColorGradientRamp;
1359 {
1360 twoColorGradientRamp = std::make_unique< QgsGradientColorRamp >( color1, color2 );
1361 }
1362
1363 //no stroke for shapeburst fills
1364 p->setPen( QPen( Qt::NoPen ) );
1365
1366 //calculate margin size in pixels so that QImage of polygon has sufficient space to draw the full blur effect
1367 int sideBuffer = 4 + ( blurRadius + 2 ) * 4;
1368 //create a QImage to draw shapeburst in
1369 int pointsWidth = static_cast< int >( std::round( points.boundingRect().width() ) );
1370 int pointsHeight = static_cast< int >( std::round( points.boundingRect().height() ) );
1371 int imWidth = pointsWidth + ( sideBuffer * 2 );
1372 int imHeight = pointsHeight + ( sideBuffer * 2 );
1373
1374 // these are all potentially very expensive operations, so check regularly if the job is canceled and abort responsively
1375 if ( context.renderContext().feedback() && context.renderContext().feedback()->isCanceled() )
1376 return;
1377
1378 std::unique_ptr< QImage > fillImage = std::make_unique< QImage >( imWidth,
1379 imHeight, QImage::Format_ARGB32_Premultiplied );
1380 if ( fillImage->isNull() )
1381 {
1382 QgsMessageLog::logMessage( QObject::tr( "Could not allocate sufficient memory for shapeburst fill" ) );
1383 return;
1384 }
1385
1386 if ( context.renderContext().feedback() && context.renderContext().feedback()->isCanceled() )
1387 return;
1388
1389 //also create an image to store the alpha channel
1390 std::unique_ptr< QImage > alphaImage = std::make_unique< QImage >( fillImage->width(), fillImage->height(), QImage::Format_ARGB32_Premultiplied );
1391 if ( alphaImage->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 //Fill this image with black. Initially the distance transform is drawn in greyscale, where black pixels have zero distance from the
1401 //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
1402 //polygon in white. The distance transform function then fills in the correct distance values for the white pixels.
1403 fillImage->fill( Qt::black );
1404
1405 if ( context.renderContext().feedback() && context.renderContext().feedback()->isCanceled() )
1406 return;
1407
1408 //initially fill the alpha channel image with a transparent color
1409 alphaImage->fill( Qt::transparent );
1410
1411 if ( context.renderContext().feedback() && context.renderContext().feedback()->isCanceled() )
1412 return;
1413
1414 //now, draw the polygon in the alpha channel image
1415 QPainter imgPainter;
1416 imgPainter.begin( alphaImage.get() );
1417 imgPainter.setRenderHint( QPainter::Antialiasing, true );
1418 imgPainter.setBrush( QBrush( Qt::white ) );
1419 imgPainter.setPen( QPen( Qt::black ) );
1420 imgPainter.translate( -points.boundingRect().left() + sideBuffer, - points.boundingRect().top() + sideBuffer );
1421 _renderPolygon( &imgPainter, points, rings, context );
1422 imgPainter.end();
1423
1424 if ( context.renderContext().feedback() && context.renderContext().feedback()->isCanceled() )
1425 return;
1426
1427 //now that we have a render of the polygon in white, draw this onto the shapeburst fill image too
1428 //(this avoids calling _renderPolygon twice, since that can be slow)
1429 imgPainter.begin( fillImage.get() );
1430 if ( !ignoreRings )
1431 {
1432 imgPainter.drawImage( 0, 0, *alphaImage );
1433 }
1434 else
1435 {
1436 //using ignore rings mode, so the alpha image can't be used
1437 //directly as the alpha channel contains polygon rings and we need
1438 //to draw now without any rings
1439 imgPainter.setBrush( QBrush( Qt::white ) );
1440 imgPainter.setPen( QPen( Qt::black ) );
1441 imgPainter.translate( -points.boundingRect().left() + sideBuffer, - points.boundingRect().top() + sideBuffer );
1442 _renderPolygon( &imgPainter, points, nullptr, context );
1443 }
1444 imgPainter.end();
1445
1446 if ( context.renderContext().feedback() && context.renderContext().feedback()->isCanceled() )
1447 return;
1448
1449 //apply distance transform to image, uses the current color ramp to calculate final pixel colors
1450 double *dtArray = distanceTransform( fillImage.get(), context.renderContext() );
1451
1452 //copy distance transform values back to QImage, shading by appropriate color ramp
1453 dtArrayToQImage( dtArray, fillImage.get(), mColorType == Qgis::GradientColorSource::SimpleTwoColor ? twoColorGradientRamp.get() : mGradientRamp.get(),
1454 context.renderContext(), useWholeShape, outputPixelMaxDist );
1455 if ( context.opacity() < 1 )
1456 {
1457 QgsImageOperation::multiplyOpacity( *fillImage, context.opacity(), context.renderContext().feedback() );
1458 }
1459
1460 //clean up some variables
1461 delete [] dtArray;
1462
1463 //apply blur if desired
1464 if ( blurRadius > 0 )
1465 {
1466 QgsImageOperation::stackBlur( *fillImage, blurRadius, false, context.renderContext().feedback() );
1467 }
1468
1469 //apply alpha channel to distance transform image, so that areas outside the polygon are transparent
1470 imgPainter.begin( fillImage.get() );
1471 imgPainter.setCompositionMode( QPainter::CompositionMode_DestinationIn );
1472 imgPainter.drawImage( 0, 0, *alphaImage );
1473 imgPainter.end();
1474 //we're finished with the alpha channel image now
1475 alphaImage.reset();
1476
1477 //draw shapeburst image in correct place in the destination painter
1478
1479 QgsScopedQPainterState painterState( p );
1480 QPointF offset = mOffset;
1482 {
1485 bool ok = false;
1486 const QPointF res = QgsSymbolLayerUtils::toPoint( val, &ok );
1487 if ( ok )
1488 offset = res;
1489 }
1490 if ( !offset.isNull() )
1491 {
1492 offset.setX( context.renderContext().convertToPainterUnits( offset.x(), mOffsetUnit, mOffsetMapUnitScale ) );
1493 offset.setY( context.renderContext().convertToPainterUnits( offset.y(), mOffsetUnit, mOffsetMapUnitScale ) );
1494 p->translate( offset );
1495 }
1496
1497 p->drawImage( points.boundingRect().left() - sideBuffer, points.boundingRect().top() - sideBuffer, *fillImage );
1498
1499 if ( !offset.isNull() )
1500 {
1501 p->translate( -offset );
1502 }
1503}
1504
1505//fast distance transform code, adapted from http://cs.brown.edu/~pff/dt/
1506
1507/* distance transform of a 1d function using squared distance */
1508void QgsShapeburstFillSymbolLayer::distanceTransform1d( double *f, int n, int *v, double *z, double *d )
1509{
1510 int k = 0;
1511 v[0] = 0;
1512 z[0] = -INF;
1513 z[1] = + INF;
1514 for ( int q = 1; q <= n - 1; q++ )
1515 {
1516 double s = ( ( f[q] + static_cast< double >( q ) * q ) - ( f[v[k]] + ( static_cast< double >( v[k] ) * v[k] ) ) ) / ( 2 * q - 2 * v[k] );
1517 while ( s <= z[k] )
1518 {
1519 k--;
1520 s = ( ( f[q] + static_cast< double >( q ) * q ) - ( f[v[k]] + ( static_cast< double >( v[k] ) * v[k] ) ) ) / ( 2 * q - 2 * v[k] );
1521 }
1522 k++;
1523 v[k] = q;
1524 z[k] = s;
1525 z[k + 1] = + INF;
1526 }
1527
1528 k = 0;
1529 for ( int q = 0; q <= n - 1; q++ )
1530 {
1531 while ( z[k + 1] < q )
1532 k++;
1533 d[q] = static_cast< double >( q - v[k] ) * ( q - v[k] ) + f[v[k]];
1534 }
1535}
1536
1537/* distance transform of 2d function using squared distance */
1538void QgsShapeburstFillSymbolLayer::distanceTransform2d( double *im, int width, int height, QgsRenderContext &context )
1539{
1540 int maxDimension = std::max( width, height );
1541 double *f = new double[ maxDimension ];
1542 int *v = new int[ maxDimension ];
1543 double *z = new double[ maxDimension + 1 ];
1544 double *d = new double[ maxDimension ];
1545
1546 // transform along columns
1547 for ( int x = 0; x < width; x++ )
1548 {
1549 if ( context.renderingStopped() )
1550 break;
1551
1552 for ( int y = 0; y < height; y++ )
1553 {
1554 f[y] = im[ x + static_cast< std::size_t>( y ) * width ];
1555 }
1556 distanceTransform1d( f, height, v, z, d );
1557 for ( int y = 0; y < height; y++ )
1558 {
1559 im[ x + static_cast< std::size_t>( y ) * width ] = d[y];
1560 }
1561 }
1562
1563 // transform along rows
1564 for ( int y = 0; y < height; y++ )
1565 {
1566 if ( context.renderingStopped() )
1567 break;
1568
1569 for ( int x = 0; x < width; x++ )
1570 {
1571 f[x] = im[ x + static_cast< std::size_t>( y ) * width ];
1572 }
1573 distanceTransform1d( f, width, v, z, d );
1574 for ( int x = 0; x < width; x++ )
1575 {
1576 im[ x + static_cast< std::size_t>( y ) * width ] = d[x];
1577 }
1578 }
1579
1580 delete [] d;
1581 delete [] f;
1582 delete [] v;
1583 delete [] z;
1584}
1585
1586/* distance transform of a binary QImage */
1587double *QgsShapeburstFillSymbolLayer::distanceTransform( QImage *im, QgsRenderContext &context )
1588{
1589 int width = im->width();
1590 int height = im->height();
1591
1592 double *dtArray = new double[static_cast< std::size_t>( width ) * height];
1593
1594 //load qImage to array
1595 QRgb tmpRgb;
1596 std::size_t idx = 0;
1597 for ( int heightIndex = 0; heightIndex < height; ++heightIndex )
1598 {
1599 if ( context.renderingStopped() )
1600 break;
1601
1602 const QRgb *scanLine = reinterpret_cast< const QRgb * >( im->constScanLine( heightIndex ) );
1603 for ( int widthIndex = 0; widthIndex < width; ++widthIndex )
1604 {
1605 tmpRgb = scanLine[widthIndex];
1606 if ( qRed( tmpRgb ) == 0 )
1607 {
1608 //black pixel, so zero distance
1609 dtArray[ idx ] = 0;
1610 }
1611 else
1612 {
1613 //white pixel, so initially set distance as infinite
1614 dtArray[ idx ] = INF;
1615 }
1616 idx++;
1617 }
1618 }
1619
1620 //calculate squared distance transform
1621 distanceTransform2d( dtArray, width, height, context );
1622
1623 return dtArray;
1624}
1625
1626void QgsShapeburstFillSymbolLayer::dtArrayToQImage( double *array, QImage *im, QgsColorRamp *ramp, QgsRenderContext &context, bool useWholeShape, int maxPixelDistance )
1627{
1628 int width = im->width();
1629 int height = im->height();
1630
1631 //find maximum distance value
1632 double maxDistanceValue;
1633
1634 if ( useWholeShape )
1635 {
1636 //no max distance specified in symbol properties, so calculate from maximum value in distance transform results
1637 double dtMaxValue = array[0];
1638 for ( std::size_t i = 1; i < static_cast< std::size_t >( width ) * height; ++i )
1639 {
1640 if ( array[i] > dtMaxValue )
1641 {
1642 dtMaxValue = array[i];
1643 }
1644 }
1645
1646 //values in distance transform are squared
1647 maxDistanceValue = std::sqrt( dtMaxValue );
1648 }
1649 else
1650 {
1651 //use max distance set in symbol properties
1652 maxDistanceValue = maxPixelDistance;
1653 }
1654
1655 //update the pixels in the provided QImage
1656 std::size_t idx = 0;
1657 double squaredVal = 0;
1658 double pixVal = 0;
1659
1660 for ( int heightIndex = 0; heightIndex < height; ++heightIndex )
1661 {
1662 if ( context.renderingStopped() )
1663 break;
1664
1665 QRgb *scanLine = reinterpret_cast< QRgb * >( im->scanLine( heightIndex ) );
1666 for ( int widthIndex = 0; widthIndex < width; ++widthIndex )
1667 {
1668 //result of distance transform
1669 squaredVal = array[idx];
1670
1671 //scale result to fit in the range [0, 1]
1672 if ( maxDistanceValue > 0 )
1673 {
1674 pixVal = squaredVal > 0 ? std::min( ( std::sqrt( squaredVal ) / maxDistanceValue ), 1.0 ) : 0;
1675 }
1676 else
1677 {
1678 pixVal = 1.0;
1679 }
1680
1681 //convert value to color from ramp
1682 //premultiply ramp color since we are storing this in a ARGB32_Premultiplied QImage
1683 scanLine[widthIndex] = qPremultiply( ramp->color( pixVal ).rgba() );
1684 idx++;
1685 }
1686 }
1687}
1688
1690{
1691 QVariantMap map;
1692 map[QStringLiteral( "color" )] = QgsColorUtils::colorToString( mColor );
1693 map[QStringLiteral( "gradient_color2" )] = QgsColorUtils::colorToString( mColor2 );
1694 map[QStringLiteral( "color_type" )] = QString::number( static_cast< int >( mColorType ) );
1695 map[QStringLiteral( "blur_radius" )] = QString::number( mBlurRadius );
1696 map[QStringLiteral( "use_whole_shape" )] = QString::number( mUseWholeShape );
1697 map[QStringLiteral( "max_distance" )] = QString::number( mMaxDistance );
1698 map[QStringLiteral( "distance_unit" )] = QgsUnitTypes::encodeUnit( mDistanceUnit );
1699 map[QStringLiteral( "distance_map_unit_scale" )] = QgsSymbolLayerUtils::encodeMapUnitScale( mDistanceMapUnitScale );
1700 map[QStringLiteral( "ignore_rings" )] = QString::number( mIgnoreRings );
1701 map[QStringLiteral( "offset" )] = QgsSymbolLayerUtils::encodePoint( mOffset );
1702 map[QStringLiteral( "offset_unit" )] = QgsUnitTypes::encodeUnit( mOffsetUnit );
1703 map[QStringLiteral( "offset_map_unit_scale" )] = QgsSymbolLayerUtils::encodeMapUnitScale( mOffsetMapUnitScale );
1704 if ( mGradientRamp )
1705 {
1706 map.insert( mGradientRamp->properties() );
1707 }
1708
1709 return map;
1710}
1711
1713{
1714 std::unique_ptr< QgsShapeburstFillSymbolLayer > sl = std::make_unique< QgsShapeburstFillSymbolLayer >( mColor, mColor2, mColorType, mBlurRadius, mUseWholeShape, mMaxDistance );
1715 if ( mGradientRamp )
1716 {
1717 sl->setColorRamp( mGradientRamp->clone() );
1718 }
1719 sl->setDistanceUnit( mDistanceUnit );
1720 sl->setDistanceMapUnitScale( mDistanceMapUnitScale );
1721 sl->setIgnoreRings( mIgnoreRings );
1722 sl->setOffset( mOffset );
1723 sl->setOffsetUnit( mOffsetUnit );
1724 sl->setOffsetMapUnitScale( mOffsetMapUnitScale );
1725 copyDataDefinedProperties( sl.get() );
1726 copyPaintEffect( sl.get() );
1727 return sl.release();
1728}
1729
1731{
1732 double offsetBleed = context.convertToPainterUnits( std::max( std::fabs( mOffset.x() ), std::fabs( mOffset.y() ) ), mOffsetUnit, mOffsetMapUnitScale );
1733 return offsetBleed;
1734}
1735
1740
1742{
1743 mDistanceUnit = unit;
1744 mOffsetUnit = unit;
1745}
1746
1748{
1749 if ( mDistanceUnit == mOffsetUnit )
1750 {
1751 return mDistanceUnit;
1752 }
1754}
1755
1757{
1758 return mDistanceUnit == Qgis::RenderUnit::MapUnits || mDistanceUnit == Qgis::RenderUnit::MetersInMapUnits
1759 || mOffsetUnit == Qgis::RenderUnit::MapUnits || mOffsetUnit == Qgis::RenderUnit::MetersInMapUnits;
1760}
1761
1763{
1764 mDistanceMapUnitScale = scale;
1765 mOffsetMapUnitScale = scale;
1766}
1767
1769{
1770 if ( mDistanceMapUnitScale == mOffsetMapUnitScale )
1771 {
1772 return mDistanceMapUnitScale;
1773 }
1774 return QgsMapUnitScale();
1775}
1776
1777
1778//QgsImageFillSymbolLayer
1779
1783
1785
1786void QgsImageFillSymbolLayer::renderPolygon( const QPolygonF &points, const QVector<QPolygonF> *rings, QgsSymbolRenderContext &context )
1787{
1788 QPainter *p = context.renderContext().painter();
1789 if ( !p )
1790 {
1791 return;
1792 }
1793
1795 applyDataDefinedSettings( context );
1796
1797 p->setPen( QPen( Qt::NoPen ) );
1798
1799 QTransform bkTransform = mBrush.transform();
1800 if ( applyBrushTransformFromContext( &context ) && !context.renderContext().textureOrigin().isNull() )
1801 {
1802 QPointF leftCorner = context.renderContext().textureOrigin();
1803 QTransform t = mBrush.transform();
1804 t.translate( leftCorner.x(), leftCorner.y() );
1805 mBrush.setTransform( t );
1806 }
1807 else
1808 {
1809 QTransform t = mBrush.transform();
1810 t.translate( 0, 0 );
1811 mBrush.setTransform( t );
1812 }
1813
1814 const bool useSelectedColor = shouldRenderUsingSelectionColor( context );
1815 if ( useSelectedColor )
1816 {
1817 QColor selColor = context.renderContext().selectionColor();
1818 p->setBrush( QBrush( selColor ) );
1819 _renderPolygon( p, points, rings, context );
1820 }
1821
1822 if ( !qgsDoubleNear( mNextAngle, 0.0 ) )
1823 {
1824 QTransform t = mBrush.transform();
1825 t.rotate( mNextAngle );
1826 mBrush.setTransform( t );
1827 }
1828 p->setBrush( mBrush );
1829 _renderPolygon( p, points, rings, context );
1830
1831 mBrush.setTransform( bkTransform );
1832}
1833
1838
1843
1848
1853
1864
1866{
1867 return Qt::SolidLine;
1868#if 0
1869 if ( !mStroke )
1870 {
1871 return Qt::SolidLine;
1872 }
1873 else
1874 {
1875 return mStroke->dxfPenStyle();
1876 }
1877#endif //0
1878}
1879
1881{
1882 QVariantMap map;
1883 map.insert( QStringLiteral( "coordinate_reference" ), QgsSymbolLayerUtils::encodeCoordinateReference( mCoordinateReference ) );
1884 return map;
1885}
1886
1905
1906
1907//QgsSVGFillSymbolLayer
1908
1909QgsSVGFillSymbolLayer::QgsSVGFillSymbolLayer( const QString &svgFilePath, double width, double angle )
1911 , mPatternWidth( width )
1912{
1913 mStrokeWidth = 0.3;
1914 mAngle = angle;
1915 mColor = QColor( 255, 255, 255 );
1917}
1918
1919QgsSVGFillSymbolLayer::QgsSVGFillSymbolLayer( const QByteArray &svgData, double width, double angle )
1921 , mPatternWidth( width )
1922 , mSvgData( svgData )
1923{
1924 storeViewBox();
1925 mStrokeWidth = 0.3;
1926 mAngle = angle;
1927 mColor = QColor( 255, 255, 255 );
1928 setDefaultSvgParams();
1929}
1930
1932
1934{
1936 mPatternWidthUnit = unit;
1937 mSvgStrokeWidthUnit = unit;
1938 mStrokeWidthUnit = unit;
1939 if ( mStroke )
1940 mStroke->setOutputUnit( unit );
1941}
1942
1944{
1946 if ( mPatternWidthUnit != unit || mSvgStrokeWidthUnit != unit || mStrokeWidthUnit != unit )
1947 {
1949 }
1950 return unit;
1951}
1952
1954{
1956 mPatternWidthMapUnitScale = scale;
1957 mSvgStrokeWidthMapUnitScale = scale;
1958}
1959
1961{
1962 if ( QgsImageFillSymbolLayer::mapUnitScale() == mPatternWidthMapUnitScale &&
1963 mPatternWidthMapUnitScale == mSvgStrokeWidthMapUnitScale &&
1964 mSvgStrokeWidthMapUnitScale == mStrokeWidthMapUnitScale )
1965 {
1966 return mPatternWidthMapUnitScale;
1967 }
1968 return QgsMapUnitScale();
1969}
1970
1971void QgsSVGFillSymbolLayer::setSvgFilePath( const QString &svgPath )
1972{
1973 mSvgData = QgsApplication::svgCache()->getImageData( svgPath );
1974 storeViewBox();
1975
1976 mSvgFilePath = svgPath;
1977 setDefaultSvgParams();
1978}
1979
1980QgsSymbolLayer *QgsSVGFillSymbolLayer::create( const QVariantMap &properties )
1981{
1982 QByteArray data;
1983 double width = 20;
1984 QString svgFilePath;
1985 double angle = 0.0;
1986
1987 if ( properties.contains( QStringLiteral( "width" ) ) )
1988 {
1989 width = properties[QStringLiteral( "width" )].toDouble();
1990 }
1991 if ( properties.contains( QStringLiteral( "svgFile" ) ) )
1992 {
1993 svgFilePath = properties[QStringLiteral( "svgFile" )].toString();
1994 }
1995 if ( properties.contains( QStringLiteral( "angle" ) ) )
1996 {
1997 angle = properties[QStringLiteral( "angle" )].toDouble();
1998 }
1999
2000 std::unique_ptr< QgsSVGFillSymbolLayer > symbolLayer;
2001 if ( !svgFilePath.isEmpty() )
2002 {
2003 symbolLayer = std::make_unique< QgsSVGFillSymbolLayer >( svgFilePath, width, angle );
2004 }
2005 else
2006 {
2007 if ( properties.contains( QStringLiteral( "data" ) ) )
2008 {
2009 data = QByteArray::fromHex( properties[QStringLiteral( "data" )].toString().toLocal8Bit() );
2010 }
2011 symbolLayer = std::make_unique< QgsSVGFillSymbolLayer >( data, width, angle );
2012 }
2013
2014 //svg parameters
2015 if ( properties.contains( QStringLiteral( "svgFillColor" ) ) )
2016 {
2017 //pre 2.5 projects used "svgFillColor"
2018 symbolLayer->setSvgFillColor( QgsColorUtils::colorFromString( properties[QStringLiteral( "svgFillColor" )].toString() ) );
2019 }
2020 else if ( properties.contains( QStringLiteral( "color" ) ) )
2021 {
2022 symbolLayer->setSvgFillColor( QgsColorUtils::colorFromString( properties[QStringLiteral( "color" )].toString() ) );
2023 }
2024 if ( properties.contains( QStringLiteral( "svgOutlineColor" ) ) )
2025 {
2026 //pre 2.5 projects used "svgOutlineColor"
2027 symbolLayer->setSvgStrokeColor( QgsColorUtils::colorFromString( properties[QStringLiteral( "svgOutlineColor" )].toString() ) );
2028 }
2029 else if ( properties.contains( QStringLiteral( "outline_color" ) ) )
2030 {
2031 symbolLayer->setSvgStrokeColor( QgsColorUtils::colorFromString( properties[QStringLiteral( "outline_color" )].toString() ) );
2032 }
2033 else if ( properties.contains( QStringLiteral( "line_color" ) ) )
2034 {
2035 symbolLayer->setSvgStrokeColor( QgsColorUtils::colorFromString( properties[QStringLiteral( "line_color" )].toString() ) );
2036 }
2037 if ( properties.contains( QStringLiteral( "svgOutlineWidth" ) ) )
2038 {
2039 //pre 2.5 projects used "svgOutlineWidth"
2040 symbolLayer->setSvgStrokeWidth( properties[QStringLiteral( "svgOutlineWidth" )].toDouble() );
2041 }
2042 else if ( properties.contains( QStringLiteral( "outline_width" ) ) )
2043 {
2044 symbolLayer->setSvgStrokeWidth( properties[QStringLiteral( "outline_width" )].toDouble() );
2045 }
2046 else if ( properties.contains( QStringLiteral( "line_width" ) ) )
2047 {
2048 symbolLayer->setSvgStrokeWidth( properties[QStringLiteral( "line_width" )].toDouble() );
2049 }
2050
2051 //units
2052 if ( properties.contains( QStringLiteral( "pattern_width_unit" ) ) )
2053 {
2054 symbolLayer->setPatternWidthUnit( QgsUnitTypes::decodeRenderUnit( properties[QStringLiteral( "pattern_width_unit" )].toString() ) );
2055 }
2056 if ( properties.contains( QStringLiteral( "pattern_width_map_unit_scale" ) ) )
2057 {
2058 symbolLayer->setPatternWidthMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( properties[QStringLiteral( "pattern_width_map_unit_scale" )].toString() ) );
2059 }
2060 if ( properties.contains( QStringLiteral( "svg_outline_width_unit" ) ) )
2061 {
2062 symbolLayer->setSvgStrokeWidthUnit( QgsUnitTypes::decodeRenderUnit( properties[QStringLiteral( "svg_outline_width_unit" )].toString() ) );
2063 }
2064 if ( properties.contains( QStringLiteral( "svg_outline_width_map_unit_scale" ) ) )
2065 {
2066 symbolLayer->setSvgStrokeWidthMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( properties[QStringLiteral( "svg_outline_width_map_unit_scale" )].toString() ) );
2067 }
2068 if ( properties.contains( QStringLiteral( "outline_width_unit" ) ) )
2069 {
2070 symbolLayer->setStrokeWidthUnit( QgsUnitTypes::decodeRenderUnit( properties[QStringLiteral( "outline_width_unit" )].toString() ) );
2071 }
2072 if ( properties.contains( QStringLiteral( "outline_width_map_unit_scale" ) ) )
2073 {
2074 symbolLayer->setStrokeWidthMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( properties[QStringLiteral( "outline_width_map_unit_scale" )].toString() ) );
2075 }
2076
2077 if ( properties.contains( QStringLiteral( "parameters" ) ) )
2078 {
2079 const QVariantMap parameters = properties[QStringLiteral( "parameters" )].toMap();
2080 symbolLayer->setParameters( QgsProperty::variantMapToPropertyMap( parameters ) );
2081 }
2082
2083 symbolLayer->restoreOldDataDefinedProperties( properties );
2084
2085 return symbolLayer.release();
2086}
2087
2088void QgsSVGFillSymbolLayer::resolvePaths( QVariantMap &properties, const QgsPathResolver &pathResolver, bool saving )
2089{
2090 QVariantMap::iterator it = properties.find( QStringLiteral( "svgFile" ) );
2091 if ( it != properties.end() )
2092 {
2093 if ( saving )
2094 it.value() = QgsSymbolLayerUtils::svgSymbolPathToName( it.value().toString(), pathResolver );
2095 else
2096 it.value() = QgsSymbolLayerUtils::svgSymbolNameToPath( it.value().toString(), pathResolver );
2097 }
2098}
2099
2101{
2102 return QStringLiteral( "SVGFill" );
2103}
2104
2105void QgsSVGFillSymbolLayer::applyPattern( QBrush &brush, const QString &svgFilePath, double patternWidth, Qgis::RenderUnit patternWidthUnit,
2106 const QColor &svgFillColor, const QColor &svgStrokeColor, double svgStrokeWidth,
2107 Qgis::RenderUnit svgStrokeWidthUnit, const QgsSymbolRenderContext &context,
2108 const QgsMapUnitScale &patternWidthMapUnitScale, const QgsMapUnitScale &svgStrokeWidthMapUnitScale, const QgsStringMap svgParameters )
2109{
2110 if ( mSvgViewBox.isNull() )
2111 {
2112 return;
2113 }
2114
2116
2117 if ( static_cast< int >( size ) < 1.0 || 10000.0 < size )
2118 {
2119 brush.setTextureImage( QImage() );
2120 }
2121 else
2122 {
2123 bool fitsInCache = true;
2125 QImage patternImage = QgsApplication::svgCache()->svgAsImage( svgFilePath, size, svgFillColor, svgStrokeColor, strokeWidth,
2126 context.renderContext().scaleFactor(), fitsInCache, 0, ( context.renderContext().flags() & Qgis::RenderContextFlag::RenderBlocking ), svgParameters );
2127 if ( !fitsInCache )
2128 {
2129 QPicture patternPict = QgsApplication::svgCache()->svgAsPicture( svgFilePath, size, svgFillColor, svgStrokeColor, strokeWidth,
2130 context.renderContext().scaleFactor(), false, 0, ( context.renderContext().flags() & Qgis::RenderContextFlag::RenderBlocking ) );
2131 double hwRatio = 1.0;
2132 if ( patternPict.width() > 0 )
2133 {
2134 hwRatio = static_cast< double >( patternPict.height() ) / static_cast< double >( patternPict.width() );
2135 }
2136 patternImage = QImage( static_cast< int >( size ), static_cast< int >( size * hwRatio ), QImage::Format_ARGB32_Premultiplied );
2137 patternImage.fill( 0 ); // transparent background
2138
2139 QPainter p( &patternImage );
2140 p.drawPicture( QPointF( size / 2, size * hwRatio / 2 ), patternPict );
2141 }
2142
2143 QTransform brushTransform;
2144 if ( !qgsDoubleNear( context.opacity(), 1.0 ) )
2145 {
2146 QImage transparentImage = patternImage.copy();
2147 QgsSymbolLayerUtils::multiplyImageOpacity( &transparentImage, context.opacity() );
2148 brush.setTextureImage( transparentImage );
2149 }
2150 else
2151 {
2152 brush.setTextureImage( patternImage );
2153 }
2154 brush.setTransform( brushTransform );
2155 }
2156}
2157
2159{
2160 QgsStringMap evaluatedParameters = QgsSymbolLayerUtils::evaluatePropertiesMap( mParameters, context.renderContext().expressionContext() );
2161
2162 applyPattern( mBrush, mSvgFilePath, mPatternWidth, mPatternWidthUnit, mColor, mSvgStrokeColor, mSvgStrokeWidth, mSvgStrokeWidthUnit, context, mPatternWidthMapUnitScale, mSvgStrokeWidthMapUnitScale, evaluatedParameters );
2163
2164 if ( mStroke )
2165 {
2166 mStroke->setRenderHints( mStroke->renderHints() | Qgis::SymbolRenderHint::IsSymbolLayerSubSymbol );
2167 mStroke->startRender( context.renderContext(), context.fields() );
2168 }
2169}
2170
2172{
2173 if ( mStroke )
2174 {
2175 mStroke->stopRender( context.renderContext() );
2176 }
2177}
2178
2179void QgsSVGFillSymbolLayer::renderPolygon( const QPolygonF &points, const QVector<QPolygonF> *rings, QgsSymbolRenderContext &context )
2180{
2181 QgsImageFillSymbolLayer::renderPolygon( points, rings, context );
2182
2183 if ( mStroke )
2184 {
2185 const bool useSelectedColor = SELECT_FILL_BORDER && shouldRenderUsingSelectionColor( context );
2186 mStroke->renderPolyline( points, context.feature(), context.renderContext(), -1, useSelectedColor );
2187 if ( rings )
2188 {
2189 for ( auto ringIt = rings->constBegin(); ringIt != rings->constEnd(); ++ringIt )
2190 {
2191 mStroke->renderPolyline( *ringIt, context.feature(), context.renderContext(), -1, useSelectedColor );
2192 }
2193 }
2194 }
2195}
2196
2198{
2199 QVariantMap map;
2200 if ( !mSvgFilePath.isEmpty() )
2201 {
2202 map.insert( QStringLiteral( "svgFile" ), mSvgFilePath );
2203 }
2204 else
2205 {
2206 map.insert( QStringLiteral( "data" ), QString( mSvgData.toHex() ) );
2207 }
2208
2209 map.insert( QStringLiteral( "width" ), QString::number( mPatternWidth ) );
2210 map.insert( QStringLiteral( "angle" ), QString::number( mAngle ) );
2211
2212 //svg parameters
2213 map.insert( QStringLiteral( "color" ), QgsColorUtils::colorToString( mColor ) );
2214 map.insert( QStringLiteral( "outline_color" ), QgsColorUtils::colorToString( mSvgStrokeColor ) );
2215 map.insert( QStringLiteral( "outline_width" ), QString::number( mSvgStrokeWidth ) );
2216
2217 //units
2218 map.insert( QStringLiteral( "pattern_width_unit" ), QgsUnitTypes::encodeUnit( mPatternWidthUnit ) );
2219 map.insert( QStringLiteral( "pattern_width_map_unit_scale" ), QgsSymbolLayerUtils::encodeMapUnitScale( mPatternWidthMapUnitScale ) );
2220 map.insert( QStringLiteral( "svg_outline_width_unit" ), QgsUnitTypes::encodeUnit( mSvgStrokeWidthUnit ) );
2221 map.insert( QStringLiteral( "svg_outline_width_map_unit_scale" ), QgsSymbolLayerUtils::encodeMapUnitScale( mSvgStrokeWidthMapUnitScale ) );
2222 map.insert( QStringLiteral( "outline_width_unit" ), QgsUnitTypes::encodeUnit( mStrokeWidthUnit ) );
2223 map.insert( QStringLiteral( "outline_width_map_unit_scale" ), QgsSymbolLayerUtils::encodeMapUnitScale( mStrokeWidthMapUnitScale ) );
2224
2225 map[QStringLiteral( "parameters" )] = QgsProperty::propertyMapToVariantMap( mParameters );
2226
2227 return map;
2228}
2229
2231{
2232 std::unique_ptr< QgsSVGFillSymbolLayer > clonedLayer;
2233 if ( !mSvgFilePath.isEmpty() )
2234 {
2235 clonedLayer = std::make_unique< QgsSVGFillSymbolLayer >( mSvgFilePath, mPatternWidth, mAngle );
2236 clonedLayer->setSvgFillColor( mColor );
2237 clonedLayer->setSvgStrokeColor( mSvgStrokeColor );
2238 clonedLayer->setSvgStrokeWidth( mSvgStrokeWidth );
2239 }
2240 else
2241 {
2242 clonedLayer = std::make_unique< QgsSVGFillSymbolLayer >( mSvgData, mPatternWidth, mAngle );
2243 }
2244
2245 clonedLayer->setPatternWidthUnit( mPatternWidthUnit );
2246 clonedLayer->setPatternWidthMapUnitScale( mPatternWidthMapUnitScale );
2247 clonedLayer->setSvgStrokeWidthUnit( mSvgStrokeWidthUnit );
2248 clonedLayer->setSvgStrokeWidthMapUnitScale( mSvgStrokeWidthMapUnitScale );
2249 clonedLayer->setStrokeWidthUnit( mStrokeWidthUnit );
2250 clonedLayer->setStrokeWidthMapUnitScale( mStrokeWidthMapUnitScale );
2251
2252 clonedLayer->setParameters( mParameters );
2253
2254 if ( mStroke )
2255 {
2256 clonedLayer->setSubSymbol( mStroke->clone() );
2257 }
2258 copyDataDefinedProperties( clonedLayer.get() );
2259 copyPaintEffect( clonedLayer.get() );
2260 return clonedLayer.release();
2261}
2262
2263void QgsSVGFillSymbolLayer::toSld( QDomDocument &doc, QDomElement &element, const QVariantMap &props ) const
2264{
2265 QDomElement symbolizerElem = doc.createElement( QStringLiteral( "se:PolygonSymbolizer" ) );
2266 if ( !props.value( QStringLiteral( "uom" ), QString() ).toString().isEmpty() )
2267 symbolizerElem.setAttribute( QStringLiteral( "uom" ), props.value( QStringLiteral( "uom" ), QString() ).toString() );
2268 element.appendChild( symbolizerElem );
2269
2270 QgsSymbolLayerUtils::createGeometryElement( doc, symbolizerElem, props.value( QStringLiteral( "geom" ), QString() ).toString() );
2271
2272 QDomElement fillElem = doc.createElement( QStringLiteral( "se:Fill" ) );
2273 symbolizerElem.appendChild( fillElem );
2274
2275 QDomElement graphicFillElem = doc.createElement( QStringLiteral( "se:GraphicFill" ) );
2276 fillElem.appendChild( graphicFillElem );
2277
2278 QDomElement graphicElem = doc.createElement( QStringLiteral( "se:Graphic" ) );
2279 graphicFillElem.appendChild( graphicElem );
2280
2281 if ( !mSvgFilePath.isEmpty() )
2282 {
2283 // encode a parametric SVG reference
2284 double patternWidth = QgsSymbolLayerUtils::rescaleUom( mPatternWidth, mPatternWidthUnit, props );
2285 double strokeWidth = QgsSymbolLayerUtils::rescaleUom( mSvgStrokeWidth, mSvgStrokeWidthUnit, props );
2286 QgsSymbolLayerUtils::parametricSvgToSld( doc, graphicElem, mSvgFilePath, mColor, patternWidth, mSvgStrokeColor, strokeWidth );
2287 }
2288 else
2289 {
2290 // TODO: create svg from data
2291 // <se:InlineContent>
2292 symbolizerElem.appendChild( doc.createComment( QStringLiteral( "SVG from data not implemented yet" ) ) );
2293 }
2294
2295 // <Rotation>
2296 QString angleFunc;
2297 bool ok;
2298 double angle = props.value( QStringLiteral( "angle" ), QStringLiteral( "0" ) ).toDouble( &ok );
2299 if ( !ok )
2300 {
2301 angleFunc = QStringLiteral( "%1 + %2" ).arg( props.value( QStringLiteral( "angle" ), QStringLiteral( "0" ) ).toString() ).arg( mAngle );
2302 }
2303 else if ( !qgsDoubleNear( angle + mAngle, 0.0 ) )
2304 {
2305 angleFunc = QString::number( angle + mAngle );
2306 }
2307 QgsSymbolLayerUtils::createRotationElement( doc, graphicElem, angleFunc );
2308
2309 if ( mStroke )
2310 {
2311 // the stroke sub symbol should be stored within the Stroke element,
2312 // but it will be stored in a separated LineSymbolizer because it could
2313 // have more than one layer
2314 mStroke->toSld( doc, element, props );
2315 }
2316}
2317
2319{
2320 return mPatternWidthUnit == Qgis::RenderUnit::MapUnits || mPatternWidthUnit == Qgis::RenderUnit::MetersInMapUnits
2321 || mSvgStrokeWidthUnit == Qgis::RenderUnit::MapUnits || mSvgStrokeWidthUnit == Qgis::RenderUnit::MetersInMapUnits;
2322}
2323
2325{
2326 return mStroke.get();
2327}
2328
2330{
2331 if ( !symbol ) //unset current stroke
2332 {
2333 mStroke.reset( nullptr );
2334 return true;
2335 }
2336
2337 if ( symbol->type() != Qgis::SymbolType::Line )
2338 {
2339 delete symbol;
2340 return false;
2341 }
2342
2343 QgsLineSymbol *lineSymbol = dynamic_cast<QgsLineSymbol *>( symbol );
2344 if ( lineSymbol )
2345 {
2346 mStroke.reset( lineSymbol );
2347 return true;
2348 }
2349
2350 delete symbol;
2351 return false;
2352}
2353
2355{
2356 if ( mStroke && mStroke->symbolLayer( 0 ) )
2357 {
2358 double subLayerBleed = mStroke->symbolLayer( 0 )->estimateMaxBleed( context );
2359 return subLayerBleed;
2360 }
2361 return 0;
2362}
2363
2365{
2366 Q_UNUSED( context )
2367 if ( !mStroke )
2368 {
2369 return QColor( Qt::black );
2370 }
2371 return mStroke->color();
2372}
2373
2374QSet<QString> QgsSVGFillSymbolLayer::usedAttributes( const QgsRenderContext &context ) const
2375{
2376 QSet<QString> attr = QgsImageFillSymbolLayer::usedAttributes( context );
2377 if ( mStroke )
2378 attr.unite( mStroke->usedAttributes( context ) );
2379 return attr;
2380}
2381
2383{
2385 return true;
2386 if ( mStroke && mStroke->hasDataDefinedProperties() )
2387 return true;
2388 return false;
2389}
2390
2392{
2393 QString path, mimeType;
2394 QColor fillColor, strokeColor;
2395 Qt::PenStyle penStyle;
2396 double size, strokeWidth;
2397
2398 QDomElement fillElem = element.firstChildElement( QStringLiteral( "Fill" ) );
2399 if ( fillElem.isNull() )
2400 return nullptr;
2401
2402 QDomElement graphicFillElem = fillElem.firstChildElement( QStringLiteral( "GraphicFill" ) );
2403 if ( graphicFillElem.isNull() )
2404 return nullptr;
2405
2406 QDomElement graphicElem = graphicFillElem.firstChildElement( QStringLiteral( "Graphic" ) );
2407 if ( graphicElem.isNull() )
2408 return nullptr;
2409
2410 if ( !QgsSymbolLayerUtils::externalGraphicFromSld( graphicElem, path, mimeType, fillColor, size ) )
2411 return nullptr;
2412
2413 if ( mimeType != QLatin1String( "image/svg+xml" ) )
2414 return nullptr;
2415
2416 QgsSymbolLayerUtils::lineFromSld( graphicElem, penStyle, strokeColor, strokeWidth );
2417
2418 double scaleFactor = 1.0;
2419 const QString uom = element.attribute( QStringLiteral( "uom" ) );
2420 Qgis::RenderUnit sldUnitSize = QgsSymbolLayerUtils::decodeSldUom( uom, &scaleFactor );
2421 size = size * scaleFactor;
2422 strokeWidth = strokeWidth * scaleFactor;
2423
2424 double angle = 0.0;
2425 QString angleFunc;
2426 if ( QgsSymbolLayerUtils::rotationFromSldElement( graphicElem, angleFunc ) )
2427 {
2428 bool ok;
2429 double d = angleFunc.toDouble( &ok );
2430 if ( ok )
2431 angle = d;
2432 }
2433
2434 std::unique_ptr< QgsSVGFillSymbolLayer > sl = std::make_unique< QgsSVGFillSymbolLayer >( path, size, angle );
2435 sl->setOutputUnit( sldUnitSize );
2436 sl->setSvgFillColor( fillColor );
2437 sl->setSvgStrokeColor( strokeColor );
2438 sl->setSvgStrokeWidth( strokeWidth );
2439
2440 // try to get the stroke
2441 QDomElement strokeElem = element.firstChildElement( QStringLiteral( "Stroke" ) );
2442 if ( !strokeElem.isNull() )
2443 {
2445 if ( l )
2446 {
2447 QgsSymbolLayerList layers;
2448 layers.append( l );
2449 sl->setSubSymbol( new QgsLineSymbol( layers ) );
2450 }
2451 }
2452
2453 return sl.release();
2454}
2455
2457{
2461 {
2462 return; //no data defined settings
2463 }
2464
2466 {
2469 }
2470
2471 double width = mPatternWidth;
2473 {
2474 context.setOriginalValueVariable( mPatternWidth );
2476 }
2477 QString svgFile = mSvgFilePath;
2479 {
2480 context.setOriginalValueVariable( mSvgFilePath );
2482 context.renderContext().pathResolver() );
2483 }
2484 QColor svgFillColor = mColor;
2486 {
2489 }
2490 QColor svgStrokeColor = mSvgStrokeColor;
2492 {
2493 context.setOriginalValueVariable( QgsSymbolLayerUtils::encodeColor( mSvgStrokeColor ) );
2495 }
2496 double strokeWidth = mSvgStrokeWidth;
2498 {
2499 context.setOriginalValueVariable( mSvgStrokeWidth );
2501 }
2502 QgsStringMap evaluatedParameters = QgsSymbolLayerUtils::evaluatePropertiesMap( mParameters, context.renderContext().expressionContext() );
2503
2504 applyPattern( mBrush, svgFile, width, mPatternWidthUnit, svgFillColor, svgStrokeColor, strokeWidth,
2505 mSvgStrokeWidthUnit, context, mPatternWidthMapUnitScale, mSvgStrokeWidthMapUnitScale, evaluatedParameters );
2506
2507}
2508
2509void QgsSVGFillSymbolLayer::storeViewBox()
2510{
2511 if ( !mSvgData.isEmpty() )
2512 {
2513 QSvgRenderer r( mSvgData );
2514 if ( r.isValid() )
2515 {
2516 mSvgViewBox = r.viewBoxF();
2517 return;
2518 }
2519 }
2520
2521 mSvgViewBox = QRectF();
2522}
2523
2524void QgsSVGFillSymbolLayer::setDefaultSvgParams()
2525{
2526 if ( mSvgFilePath.isEmpty() )
2527 {
2528 return;
2529 }
2530
2531 bool hasFillParam, hasFillOpacityParam, hasStrokeParam, hasStrokeWidthParam, hasStrokeOpacityParam;
2532 bool hasDefaultFillColor, hasDefaultFillOpacity, hasDefaultStrokeColor, hasDefaultStrokeWidth, hasDefaultStrokeOpacity;
2533 QColor defaultFillColor, defaultStrokeColor;
2534 double defaultStrokeWidth, defaultFillOpacity, defaultStrokeOpacity;
2535 QgsApplication::svgCache()->containsParams( mSvgFilePath, hasFillParam, hasDefaultFillColor, defaultFillColor,
2536 hasFillOpacityParam, hasDefaultFillOpacity, defaultFillOpacity,
2537 hasStrokeParam, hasDefaultStrokeColor, defaultStrokeColor,
2538 hasStrokeWidthParam, hasDefaultStrokeWidth, defaultStrokeWidth,
2539 hasStrokeOpacityParam, hasDefaultStrokeOpacity, defaultStrokeOpacity );
2540
2541 double newFillOpacity = hasFillOpacityParam ? mColor.alphaF() : 1.0;
2542 double newStrokeOpacity = hasStrokeOpacityParam ? mSvgStrokeColor.alphaF() : 1.0;
2543
2544 if ( hasDefaultFillColor )
2545 {
2546 mColor = defaultFillColor;
2547 mColor.setAlphaF( newFillOpacity );
2548 }
2549 if ( hasDefaultFillOpacity )
2550 {
2551 mColor.setAlphaF( defaultFillOpacity );
2552 }
2553 if ( hasDefaultStrokeColor )
2554 {
2555 mSvgStrokeColor = defaultStrokeColor;
2556 mSvgStrokeColor.setAlphaF( newStrokeOpacity );
2557 }
2558 if ( hasDefaultStrokeOpacity )
2559 {
2560 mSvgStrokeColor.setAlphaF( defaultStrokeOpacity );
2561 }
2562 if ( hasDefaultStrokeWidth )
2563 {
2564 mSvgStrokeWidth = defaultStrokeWidth;
2565 }
2566}
2567
2568void QgsSVGFillSymbolLayer::setParameters( const QMap<QString, QgsProperty> &parameters )
2569{
2570 mParameters = parameters;
2571}
2572
2573
2576{
2577 mFillLineSymbol = std::make_unique<QgsLineSymbol>( );
2578 QgsImageFillSymbolLayer::setSubSymbol( nullptr ); //no stroke
2579}
2580
2582
2584{
2585 mFillLineSymbol->setWidth( w );
2586 mLineWidth = w;
2587}
2588
2590{
2591 mFillLineSymbol->setColor( c );
2592 mColor = c;
2593}
2594
2596{
2597 return mFillLineSymbol ? mFillLineSymbol->color() : mColor;
2598}
2599
2601{
2602 if ( !symbol )
2603 {
2604 return false;
2605 }
2606
2607 if ( symbol->type() == Qgis::SymbolType::Line )
2608 {
2609 mFillLineSymbol.reset( qgis::down_cast<QgsLineSymbol *>( symbol ) );
2610 return true;
2611 }
2612 delete symbol;
2613 return false;
2614}
2615
2617{
2618 return mFillLineSymbol.get();
2619}
2620
2622{
2623 QSet<QString> attr = QgsImageFillSymbolLayer::usedAttributes( context );
2624 if ( mFillLineSymbol )
2625 attr.unite( mFillLineSymbol->usedAttributes( context ) );
2626 return attr;
2627}
2628
2630{
2632 return true;
2633 if ( mFillLineSymbol && mFillLineSymbol->hasDataDefinedProperties() )
2634 return true;
2635 return false;
2636}
2637
2639{
2640 installMasks( context, true );
2641
2642 // The base class version passes this on to the subsymbol, but we deliberately don't do that here.
2643}
2644
2646{
2647 removeMasks( context, true );
2648
2649 // The base class version passes this on to the subsymbol, but we deliberately don't do that here.
2650}
2651
2653{
2654
2655 double lineAngleRad { qDegreesToRadians( mLineAngle ) };
2656
2657 const int quadrant { static_cast<int>( lineAngleRad / M_PI_2 ) };
2658 Q_ASSERT( quadrant >= 0 && quadrant <= 3 );
2659
2660 switch ( quadrant )
2661 {
2662 case 0:
2663 {
2664 break;
2665 }
2666 case 1:
2667 {
2668 lineAngleRad -= M_PI / 2;
2669 break;
2670 }
2671 case 2:
2672 {
2673 lineAngleRad -= M_PI;
2674 break;
2675 }
2676 case 3:
2677 {
2678 lineAngleRad -= M_PI + M_PI_2;
2679 break;
2680 }
2681 }
2682
2683
2684 double distancePx { QgsSymbolLayerUtils::rescaleUom( mDistance, mDistanceUnit, {} ) };
2685
2686 QSize size { static_cast<int>( distancePx ), static_cast<int>( distancePx ) };
2687
2688 if ( static_cast<int>( mLineAngle ) % 90 != 0 )
2689 {
2690 size = QSize( static_cast<int>( distancePx / std::sin( lineAngleRad ) ), static_cast<int>( distancePx / std::cos( lineAngleRad ) ) );
2691 }
2692
2693 QPixmap pixmap( size );
2694 pixmap.fill( Qt::transparent );
2695 QPainter painter;
2696 painter.begin( &pixmap );
2697 painter.setRenderHint( QPainter::Antialiasing );
2698 QgsRenderContext renderContext = QgsRenderContext::fromQPainter( &painter );
2702 renderContext.setForceVectorOutput( true );
2703 QgsSymbolRenderContext symbolContext( renderContext, Qgis::RenderUnit::Pixels, 1.0, false, Qgis::SymbolRenderHints() );
2704
2705 std::unique_ptr< QgsLinePatternFillSymbolLayer > layerClone( clone() );
2706 layerClone->setOffset( 0 );
2707 layerClone->drawPreviewIcon( symbolContext, pixmap.size() );
2708 painter.end();
2709 return pixmap.toImage();
2710}
2711
2713{
2714 return 0;
2715}
2716
2718{
2720 mDistanceUnit = unit;
2721 mLineWidthUnit = unit;
2722 mOffsetUnit = unit;
2723
2724 if ( mFillLineSymbol )
2725 mFillLineSymbol->setOutputUnit( unit );
2726}
2727
2729{
2731 if ( mDistanceUnit != unit || mLineWidthUnit != unit || ( mOffsetUnit != unit && mOffsetUnit != Qgis::RenderUnit::Percentage ) )
2732 {
2734 }
2735 return unit;
2736}
2737
2739{
2740 return mDistanceUnit == Qgis::RenderUnit::MapUnits || mDistanceUnit == Qgis::RenderUnit::MetersInMapUnits
2741 || mLineWidthUnit == Qgis::RenderUnit::MapUnits || mLineWidthUnit == Qgis::RenderUnit::MetersInMapUnits
2742 || mOffsetUnit == Qgis::RenderUnit::MapUnits || mOffsetUnit == Qgis::RenderUnit::MetersInMapUnits;
2743}
2744
2746{
2748 mDistanceMapUnitScale = scale;
2749 mLineWidthMapUnitScale = scale;
2750 mOffsetMapUnitScale = scale;
2751}
2752
2754{
2755 if ( QgsImageFillSymbolLayer::mapUnitScale() == mDistanceMapUnitScale &&
2756 mDistanceMapUnitScale == mLineWidthMapUnitScale &&
2757 mLineWidthMapUnitScale == mOffsetMapUnitScale )
2758 {
2759 return mDistanceMapUnitScale;
2760 }
2761 return QgsMapUnitScale();
2762}
2763
2765{
2766 std::unique_ptr< QgsLinePatternFillSymbolLayer > patternLayer = std::make_unique< QgsLinePatternFillSymbolLayer >();
2767
2768 //default values
2769 double lineAngle = 45;
2770 double distance = 5;
2771 double lineWidth = 0.5;
2772 QColor color( Qt::black );
2773 double offset = 0.0;
2774
2775 if ( properties.contains( QStringLiteral( "lineangle" ) ) )
2776 {
2777 //pre 2.5 projects used "lineangle"
2778 lineAngle = properties[QStringLiteral( "lineangle" )].toDouble();
2779 }
2780 else if ( properties.contains( QStringLiteral( "angle" ) ) )
2781 {
2782 lineAngle = properties[QStringLiteral( "angle" )].toDouble();
2783 }
2784 patternLayer->setLineAngle( lineAngle );
2785
2786 if ( properties.contains( QStringLiteral( "distance" ) ) )
2787 {
2788 distance = properties[QStringLiteral( "distance" )].toDouble();
2789 }
2790 patternLayer->setDistance( distance );
2791
2792 if ( properties.contains( QStringLiteral( "linewidth" ) ) )
2793 {
2794 //pre 2.5 projects used "linewidth"
2795 lineWidth = properties[QStringLiteral( "linewidth" )].toDouble();
2796 }
2797 else if ( properties.contains( QStringLiteral( "outline_width" ) ) )
2798 {
2799 lineWidth = properties[QStringLiteral( "outline_width" )].toDouble();
2800 }
2801 else if ( properties.contains( QStringLiteral( "line_width" ) ) )
2802 {
2803 lineWidth = properties[QStringLiteral( "line_width" )].toDouble();
2804 }
2805 patternLayer->setLineWidth( lineWidth );
2806
2807 if ( properties.contains( QStringLiteral( "color" ) ) )
2808 {
2809 color = QgsColorUtils::colorFromString( properties[QStringLiteral( "color" )].toString() );
2810 }
2811 else if ( properties.contains( QStringLiteral( "outline_color" ) ) )
2812 {
2813 color = QgsColorUtils::colorFromString( properties[QStringLiteral( "outline_color" )].toString() );
2814 }
2815 else if ( properties.contains( QStringLiteral( "line_color" ) ) )
2816 {
2817 color = QgsColorUtils::colorFromString( properties[QStringLiteral( "line_color" )].toString() );
2818 }
2819 patternLayer->setColor( color );
2820
2821 if ( properties.contains( QStringLiteral( "offset" ) ) )
2822 {
2823 offset = properties[QStringLiteral( "offset" )].toDouble();
2824 }
2825 patternLayer->setOffset( offset );
2826
2827
2828 if ( properties.contains( QStringLiteral( "distance_unit" ) ) )
2829 {
2830 patternLayer->setDistanceUnit( QgsUnitTypes::decodeRenderUnit( properties[QStringLiteral( "distance_unit" )].toString() ) );
2831 }
2832 if ( properties.contains( QStringLiteral( "distance_map_unit_scale" ) ) )
2833 {
2834 patternLayer->setDistanceMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( properties[QStringLiteral( "distance_map_unit_scale" )].toString() ) );
2835 }
2836 if ( properties.contains( QStringLiteral( "line_width_unit" ) ) )
2837 {
2838 patternLayer->setLineWidthUnit( QgsUnitTypes::decodeRenderUnit( properties[QStringLiteral( "line_width_unit" )].toString() ) );
2839 }
2840 else if ( properties.contains( QStringLiteral( "outline_width_unit" ) ) )
2841 {
2842 patternLayer->setLineWidthUnit( QgsUnitTypes::decodeRenderUnit( properties[QStringLiteral( "outline_width_unit" )].toString() ) );
2843 }
2844 if ( properties.contains( QStringLiteral( "line_width_map_unit_scale" ) ) )
2845 {
2846 patternLayer->setLineWidthMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( properties[QStringLiteral( "line_width_map_unit_scale" )].toString() ) );
2847 }
2848 if ( properties.contains( QStringLiteral( "offset_unit" ) ) )
2849 {
2850 patternLayer->setOffsetUnit( QgsUnitTypes::decodeRenderUnit( properties[QStringLiteral( "offset_unit" )].toString() ) );
2851 }
2852 if ( properties.contains( QStringLiteral( "offset_map_unit_scale" ) ) )
2853 {
2854 patternLayer->setOffsetMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( properties[QStringLiteral( "offset_map_unit_scale" )].toString() ) );
2855 }
2856 if ( properties.contains( QStringLiteral( "outline_width_unit" ) ) )
2857 {
2858 patternLayer->setStrokeWidthUnit( QgsUnitTypes::decodeRenderUnit( properties[QStringLiteral( "outline_width_unit" )].toString() ) );
2859 }
2860 if ( properties.contains( QStringLiteral( "outline_width_map_unit_scale" ) ) )
2861 {
2862 patternLayer->setStrokeWidthMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( properties[QStringLiteral( "outline_width_map_unit_scale" )].toString() ) );
2863 }
2864 if ( properties.contains( QStringLiteral( "coordinate_reference" ) ) )
2865 {
2866 patternLayer->setCoordinateReference( QgsSymbolLayerUtils::decodeCoordinateReference( properties[QStringLiteral( "coordinate_reference" )].toString() ) );
2867 }
2868 if ( properties.contains( QStringLiteral( "clip_mode" ) ) )
2869 {
2870 patternLayer->setClipMode( QgsSymbolLayerUtils::decodeLineClipMode( properties.value( QStringLiteral( "clip_mode" ) ).toString() ) );
2871 }
2872
2873 patternLayer->restoreOldDataDefinedProperties( properties );
2874
2875 return patternLayer.release();
2876}
2877
2879{
2880 return QStringLiteral( "LinePatternFill" );
2881}
2882
2883bool QgsLinePatternFillSymbolLayer::applyPattern( const QgsSymbolRenderContext &context, QBrush &brush, double lineAngle, double distance )
2884{
2885 mBrush.setTextureImage( QImage() ); // set empty in case we have to return
2886
2887 if ( !mFillLineSymbol )
2888 {
2889 return true;
2890 }
2891 // We have to make a copy because marker intervals will have to be adjusted
2892 std::unique_ptr< QgsLineSymbol > fillLineSymbol( mFillLineSymbol->clone() );
2893 if ( !fillLineSymbol )
2894 {
2895 return true;
2896 }
2897
2898 const QgsRenderContext &ctx = context.renderContext();
2899 //double strokePixelWidth = lineWidth * QgsSymbolLayerUtils::pixelSizeScaleFactor( ctx, mLineWidthUnit, mLineWidthMapUnitScale );
2900 double outputPixelDist = ctx.convertToPainterUnits( distance, mDistanceUnit, mDistanceMapUnitScale );
2901 double outputPixelOffset = mOffsetUnit == Qgis::RenderUnit::Percentage ? outputPixelDist * mOffset / 100
2902 : ctx.convertToPainterUnits( mOffset, mOffsetUnit, mOffsetMapUnitScale );
2903
2904 // NOTE: this may need to be modified if we ever change from a forced rasterized/brush approach,
2905 // because potentially we may want to allow vector based line pattern fills where the first line
2906 // is offset by a large distance
2907
2908 // fix truncated pattern with larger offsets
2909 outputPixelOffset = std::fmod( outputPixelOffset, outputPixelDist );
2910 if ( outputPixelOffset > outputPixelDist / 2.0 )
2911 outputPixelOffset -= outputPixelDist;
2912
2913 // To get all patterns into image, we have to consider symbols size (estimateMaxBleed()).
2914 // For marker lines we have to get markers interval.
2915 double outputPixelBleed = 0;
2916 double outputPixelInterval = 0; // maximum interval
2917 for ( int i = 0; i < fillLineSymbol->symbolLayerCount(); i++ )
2918 {
2919 QgsSymbolLayer *layer = fillLineSymbol->symbolLayer( i );
2920 double outputPixelLayerBleed = layer->estimateMaxBleed( context.renderContext() );
2921 outputPixelBleed = std::max( outputPixelBleed, outputPixelLayerBleed );
2922
2923 QgsMarkerLineSymbolLayer *markerLineLayer = dynamic_cast<QgsMarkerLineSymbolLayer *>( layer );
2924 if ( markerLineLayer )
2925 {
2926 double outputPixelLayerInterval = ctx.convertToPainterUnits( markerLineLayer->interval(), markerLineLayer->intervalUnit(), markerLineLayer->intervalMapUnitScale() );
2927
2928 // There may be multiple marker lines with different intervals.
2929 // In theory we should find the least common multiple, but that could be too
2930 // big (multiplication of intervals in the worst case).
2931 // Because patterns without small common interval would look strange, we
2932 // believe that the longest interval should usually be sufficient.
2933 outputPixelInterval = std::max( outputPixelInterval, outputPixelLayerInterval );
2934 }
2935 }
2936
2937 if ( outputPixelInterval > 0 )
2938 {
2939 // We have to adjust marker intervals to integer pixel size to get
2940 // repeatable pattern.
2941 double intervalScale = std::round( outputPixelInterval ) / outputPixelInterval;
2942 outputPixelInterval = std::round( outputPixelInterval );
2943
2944 for ( int i = 0; i < fillLineSymbol->symbolLayerCount(); i++ )
2945 {
2946 QgsSymbolLayer *layer = fillLineSymbol->symbolLayer( i );
2947
2948 QgsMarkerLineSymbolLayer *markerLineLayer = dynamic_cast<QgsMarkerLineSymbolLayer *>( layer );
2949 if ( markerLineLayer )
2950 {
2951 markerLineLayer->setInterval( intervalScale * markerLineLayer->interval() );
2952 }
2953 }
2954 }
2955
2956 //create image
2957 int height, width;
2958 lineAngle = std::fmod( lineAngle, 360 );
2959 if ( lineAngle < 0 )
2960 lineAngle += 360;
2961 if ( qgsDoubleNear( lineAngle, 0 ) || qgsDoubleNear( lineAngle, 360 ) || qgsDoubleNear( lineAngle, 180 ) )
2962 {
2963 height = outputPixelDist;
2964 width = outputPixelInterval > 0 ? outputPixelInterval : height;
2965 }
2966 else if ( qgsDoubleNear( lineAngle, 90 ) || qgsDoubleNear( lineAngle, 270 ) )
2967 {
2968 width = outputPixelDist;
2969 height = outputPixelInterval > 0 ? outputPixelInterval : width;
2970 }
2971 else
2972 {
2973 height = outputPixelDist / std::cos( lineAngle * M_PI / 180 ); //keep perpendicular distance between lines constant
2974 width = outputPixelDist / std::sin( lineAngle * M_PI / 180 );
2975
2976 // recalculate real angle and distance after rounding to pixels
2977 lineAngle = 180 * std::atan2( static_cast< double >( height ), static_cast< double >( width ) ) / M_PI;
2978 if ( lineAngle < 0 )
2979 {
2980 lineAngle += 360.;
2981 }
2982
2983 height = std::abs( height );
2984 width = std::abs( width );
2985
2986 outputPixelDist = std::abs( height * std::cos( lineAngle * M_PI / 180 ) );
2987
2988 // Round offset to correspond to one pixel height, otherwise lines may
2989 // be shifted on tile border if offset falls close to pixel center
2990 int offsetHeight = static_cast< int >( std::round( outputPixelOffset / std::cos( lineAngle * M_PI / 180 ) ) );
2991 outputPixelOffset = offsetHeight * std::cos( lineAngle * M_PI / 180 );
2992 }
2993
2994 //depending on the angle, we might need to render into a larger image and use a subset of it
2995 double dx = 0;
2996 double dy = 0;
2997
2998 // Add buffer based on bleed but keep precisely the height/width ratio (angle)
2999 // thus we add integer multiplications of width and height covering the bleed
3000 int bufferMulti = static_cast< int >( std::max( std::ceil( outputPixelBleed / width ), std::ceil( outputPixelBleed / width ) ) );
3001
3002 // Always buffer at least once so that center of line marker in upper right corner
3003 // does not fall outside due to representation error
3004 bufferMulti = std::max( bufferMulti, 1 );
3005
3006 int xBuffer = width * bufferMulti;
3007 int yBuffer = height * bufferMulti;
3008 int innerWidth = width;
3009 int innerHeight = height;
3010 width += 2 * xBuffer;
3011 height += 2 * yBuffer;
3012
3013 //protect from zero width/height image and symbol layer from eating too much memory
3014 if ( width > 2000 || height > 2000 || width == 0 || height == 0 )
3015 {
3016 return false;
3017 }
3018
3019 QImage patternImage( width, height, QImage::Format_ARGB32 );
3020 patternImage.fill( 0 );
3021
3022 QPointF p1, p2, p3, p4, p5, p6;
3023 if ( qgsDoubleNear( lineAngle, 0.0 ) || qgsDoubleNear( lineAngle, 360.0 ) || qgsDoubleNear( lineAngle, 180.0 ) )
3024 {
3025 p1 = QPointF( 0, yBuffer );
3026 p2 = QPointF( width, yBuffer );
3027 p3 = QPointF( 0, yBuffer + innerHeight );
3028 p4 = QPointF( width, yBuffer + innerHeight );
3029 }
3030 else if ( qgsDoubleNear( lineAngle, 90.0 ) || qgsDoubleNear( lineAngle, 270.0 ) )
3031 {
3032 p1 = QPointF( xBuffer, height );
3033 p2 = QPointF( xBuffer, 0 );
3034 p3 = QPointF( xBuffer + innerWidth, height );
3035 p4 = QPointF( xBuffer + innerWidth, 0 );
3036 }
3037 else if ( lineAngle > 0 && lineAngle < 90 )
3038 {
3039 dx = outputPixelDist * std::cos( ( 90 - lineAngle ) * M_PI / 180.0 );
3040 dy = outputPixelDist * std::sin( ( 90 - lineAngle ) * M_PI / 180.0 );
3041 p1 = QPointF( 0, height );
3042 p2 = QPointF( width, 0 );
3043 p3 = QPointF( -dx, height - dy );
3044 p4 = QPointF( width - dx, -dy );
3045 p5 = QPointF( dx, height + dy );
3046 p6 = QPointF( width + dx, dy );
3047 }
3048 else if ( lineAngle > 180 && lineAngle < 270 )
3049 {
3050 dx = outputPixelDist * std::cos( ( 90 - lineAngle ) * M_PI / 180.0 );
3051 dy = outputPixelDist * std::sin( ( 90 - lineAngle ) * M_PI / 180.0 );
3052 p1 = QPointF( width, 0 );
3053 p2 = QPointF( 0, height );
3054 p3 = QPointF( width - dx, -dy );
3055 p4 = QPointF( -dx, height - dy );
3056 p5 = QPointF( width + dx, dy );
3057 p6 = QPointF( dx, height + dy );
3058 }
3059 else if ( lineAngle > 90 && lineAngle < 180 )
3060 {
3061 dy = outputPixelDist * std::cos( ( 180 - lineAngle ) * M_PI / 180 );
3062 dx = outputPixelDist * std::sin( ( 180 - lineAngle ) * M_PI / 180 );
3063 p1 = QPointF( 0, 0 );
3064 p2 = QPointF( width, height );
3065 p5 = QPointF( dx, -dy );
3066 p6 = QPointF( width + dx, height - dy );
3067 p3 = QPointF( -dx, dy );
3068 p4 = QPointF( width - dx, height + dy );
3069 }
3070 else if ( lineAngle > 270 && lineAngle < 360 )
3071 {
3072 dy = outputPixelDist * std::cos( ( 180 - lineAngle ) * M_PI / 180 );
3073 dx = outputPixelDist * std::sin( ( 180 - lineAngle ) * M_PI / 180 );
3074 p1 = QPointF( width, height );
3075 p2 = QPointF( 0, 0 );
3076 p5 = QPointF( width + dx, height - dy );
3077 p6 = QPointF( dx, -dy );
3078 p3 = QPointF( width - dx, height + dy );
3079 p4 = QPointF( -dx, dy );
3080 }
3081
3082 if ( !qgsDoubleNear( mOffset, 0.0 ) ) //shift everything
3083 {
3084 QPointF tempPt;
3085 tempPt = QgsSymbolLayerUtils::pointOnLineWithDistance( p1, p3, outputPixelDist + outputPixelOffset );
3086 p3 = QPointF( tempPt.x(), tempPt.y() );
3087 tempPt = QgsSymbolLayerUtils::pointOnLineWithDistance( p2, p4, outputPixelDist + outputPixelOffset );
3088 p4 = QPointF( tempPt.x(), tempPt.y() );
3089 tempPt = QgsSymbolLayerUtils::pointOnLineWithDistance( p1, p5, outputPixelDist - outputPixelOffset );
3090 p5 = QPointF( tempPt.x(), tempPt.y() );
3091 tempPt = QgsSymbolLayerUtils::pointOnLineWithDistance( p2, p6, outputPixelDist - outputPixelOffset );
3092 p6 = QPointF( tempPt.x(), tempPt.y() );
3093
3094 //update p1, p2 last
3095 tempPt = QgsSymbolLayerUtils::pointOnLineWithDistance( p1, p3, outputPixelOffset );
3096 p1 = QPointF( tempPt.x(), tempPt.y() );
3097 tempPt = QgsSymbolLayerUtils::pointOnLineWithDistance( p2, p4, outputPixelOffset );
3098 p2 = QPointF( tempPt.x(), tempPt.y() );
3099 }
3100
3101 QPainter p( &patternImage );
3102
3103#if 0
3104 // DEBUG: Draw rectangle
3105 p.setRenderHint( QPainter::Antialiasing, false ); // get true rect
3106 QPen pen( QColor( Qt::black ) );
3107 pen.setWidthF( 0.1 );
3108 pen.setCapStyle( Qt::FlatCap );
3109 p.setPen( pen );
3110
3111 // To see this rectangle, comment buffer cut below.
3112 // Subtract 1 because not antialiased are rendered to the right/down by 1 pixel
3113 QPolygon polygon = QPolygon() << QPoint( 0, 0 ) << QPoint( width - 1, 0 ) << QPoint( width - 1, height - 1 ) << QPoint( 0, height - 1 ) << QPoint( 0, 0 );
3114 p.drawPolygon( polygon );
3115
3116 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 );
3117 p.drawPolygon( polygon );
3118#endif
3119
3120 // Use antialiasing because without antialiasing lines are rendered to the
3121 // right and below the mathematically defined points (not symmetrical)
3122 // and such tiles become useless for are filling
3123 p.setRenderHint( QPainter::Antialiasing, true );
3124
3125 // line rendering needs context for drawing on patternImage
3126 QgsRenderContext lineRenderContext;
3127 lineRenderContext.setPainter( &p );
3128 lineRenderContext.setScaleFactor( context.renderContext().scaleFactor() );
3130 lineRenderContext.setMapToPixel( mtp );
3131 lineRenderContext.setForceVectorOutput( false );
3132 lineRenderContext.setExpressionContext( context.renderContext().expressionContext() );
3134 lineRenderContext.setDisabledSymbolLayersV2( context.renderContext().disabledSymbolLayersV2() );
3135
3136 fillLineSymbol->setRenderHints( fillLineSymbol->renderHints() | Qgis::SymbolRenderHint::IsSymbolLayerSubSymbol );
3137 fillLineSymbol->startRender( lineRenderContext, context.fields() );
3138
3139 QVector<QPolygonF> polygons;
3140 polygons.append( QPolygonF() << p1 << p2 );
3141 polygons.append( QPolygonF() << p3 << p4 );
3142 if ( !qgsDoubleNear( lineAngle, 0 ) && !qgsDoubleNear( lineAngle, 360 ) && !qgsDoubleNear( lineAngle, 90 ) && !qgsDoubleNear( lineAngle, 180 ) && !qgsDoubleNear( lineAngle, 270 ) )
3143 {
3144 polygons.append( QPolygonF() << p5 << p6 );
3145 }
3146
3147 const bool useSelectedColor = shouldRenderUsingSelectionColor( context );
3148 for ( const QPolygonF &polygon : std::as_const( polygons ) )
3149 {
3150 fillLineSymbol->renderPolyline( polygon, context.feature(), lineRenderContext, -1, useSelectedColor );
3151 }
3152
3153 fillLineSymbol->stopRender( lineRenderContext );
3154 p.end();
3155
3156 // Cut off the buffer
3157 patternImage = patternImage.copy( xBuffer, yBuffer, patternImage.width() - 2 * xBuffer, patternImage.height() - 2 * yBuffer );
3158
3159 //set image to mBrush
3160 if ( !qgsDoubleNear( context.opacity(), 1.0 ) )
3161 {
3162 QImage transparentImage = patternImage.copy();
3163 QgsSymbolLayerUtils::multiplyImageOpacity( &transparentImage, context.opacity() );
3164 brush.setTextureImage( transparentImage );
3165 }
3166 else
3167 {
3168 brush.setTextureImage( patternImage );
3169 }
3170
3171 QTransform brushTransform;
3172 brush.setTransform( brushTransform );
3173
3174 return true;
3175}
3176
3178{
3179 // if we are using a vector based output, we need to render points as vectors
3180 // (OR if the line has data defined symbology, in which case we need to evaluate this line-by-line)
3181 mRenderUsingLines = context.forceVectorRendering()
3182 || ( mFillLineSymbol && mFillLineSymbol->hasDataDefinedProperties() )
3185
3186 if ( !mRenderUsingLines )
3187 {
3188 // optimised render for screen only, use image based brush
3189 // (fallback to line rendering when pattern image will result in too large a memory footprint)
3190 mRenderUsingLines = !applyPattern( context, mBrush, mLineAngle, mDistance );
3191 }
3192
3193 if ( mRenderUsingLines && mFillLineSymbol )
3194 {
3195 mFillLineSymbol->setRenderHints( mFillLineSymbol->renderHints() | Qgis::SymbolRenderHint::IsSymbolLayerSubSymbol );
3196 mFillLineSymbol->startRender( context.renderContext(), context.fields() );
3197 mFillLineSymbolRenderStarted = true;
3198 }
3199}
3200
3202{
3203 if ( mFillLineSymbolRenderStarted )
3204 {
3205 mFillLineSymbol->stopRender( context.renderContext() );
3206 mFillLineSymbolRenderStarted = false;
3207 }
3208}
3209
3210void QgsLinePatternFillSymbolLayer::renderPolygon( const QPolygonF &points, const QVector<QPolygonF> *rings, QgsSymbolRenderContext &context )
3211{
3212 const bool useSelectedColor = shouldRenderUsingSelectionColor( context );
3213 if ( !useSelectedColor && !mRenderUsingLines )
3214 {
3215 // use image based brush for speed
3216 QgsImageFillSymbolLayer::renderPolygon( points, rings, context );
3217 return;
3218 }
3219
3220 if ( !mFillLineSymbolRenderStarted && mFillLineSymbol )
3221 {
3222 mFillLineSymbol->setRenderHints( mFillLineSymbol->renderHints() | Qgis::SymbolRenderHint::IsSymbolLayerSubSymbol );
3223 mFillLineSymbol->startRender( context.renderContext(), context.fields() );
3224 mFillLineSymbolRenderStarted = true;
3225 }
3226
3227 // vector based output - so draw line by line!
3228 QPainter *p = context.renderContext().painter();
3229 if ( !p )
3230 {
3231 return;
3232 }
3233
3234 double lineAngle = mLineAngle;
3236 {
3237 context.setOriginalValueVariable( mLineAngle );
3239 }
3240
3241 double distance = mDistance;
3243 {
3244 context.setOriginalValueVariable( mDistance );
3246 }
3247 const double outputPixelDistance = context.renderContext().convertToPainterUnits( distance, mDistanceUnit, mDistanceMapUnitScale );
3248
3249 double offset = mOffset;
3250 double outputPixelOffset = mOffsetUnit == Qgis::RenderUnit::Percentage ? outputPixelDistance * offset / 100
3251 : context.renderContext().convertToPainterUnits( offset, mOffsetUnit, mOffsetMapUnitScale );
3252
3253 // fix truncated pattern with larger offsets
3254 outputPixelOffset = std::fmod( outputPixelOffset, outputPixelDistance );
3255 if ( outputPixelOffset > outputPixelDistance / 2.0 )
3256 outputPixelOffset -= outputPixelDistance;
3257
3258 p->setPen( QPen( Qt::NoPen ) );
3259
3260 // if invalid parameters, skip out
3261 if ( qgsDoubleNear( distance, 0 ) )
3262 return;
3263
3264 p->save();
3265
3266 Qgis::LineClipMode clipMode = mClipMode;
3268 {
3270 bool ok = false;
3271 const QString valueString = mDataDefinedProperties.valueAsString( QgsSymbolLayer::Property::LineClipping, context.renderContext().expressionContext(), QString(), &ok );
3272 if ( ok )
3273 {
3274 Qgis::LineClipMode decodedMode = QgsSymbolLayerUtils::decodeLineClipMode( valueString, &ok );
3275 if ( ok )
3276 clipMode = decodedMode;
3277 }
3278 }
3279
3280 std::unique_ptr< QgsPolygon > shapePolygon;
3281 std::unique_ptr< QgsGeometryEngine > shapeEngine;
3282 switch ( clipMode )
3283 {
3285 break;
3286
3288 {
3289 shapePolygon = std::make_unique< QgsPolygon >();
3290 shapePolygon->setExteriorRing( QgsLineString::fromQPolygonF( points ) );
3291 if ( rings )
3292 {
3293 for ( const QPolygonF &ring : *rings )
3294 {
3295 shapePolygon->addInteriorRing( QgsLineString::fromQPolygonF( ring ) );
3296 }
3297 }
3298 shapeEngine.reset( QgsGeometry::createGeometryEngine( shapePolygon.get() ) );
3299 shapeEngine->prepareGeometry();
3300 break;
3301 }
3302
3304 {
3305 QPainterPath path;
3306 path.addPolygon( points );
3307 if ( rings )
3308 {
3309 for ( const QPolygonF &ring : *rings )
3310 {
3311 path.addPolygon( ring );
3312 }
3313 }
3314 p->setClipPath( path, Qt::IntersectClip );
3315 break;
3316 }
3317 }
3318
3319 const bool applyBrushTransform = applyBrushTransformFromContext( &context );
3320 const QRectF boundingRect = points.boundingRect();
3321
3322 QTransform invertedRotateTransform;
3323 double left;
3324 double top;
3325 double right;
3326 double bottom;
3327
3328 QTransform transform;
3329 if ( applyBrushTransform )
3330 {
3331 // rotation applies around center of feature
3332 transform.translate( -boundingRect.center().x(),
3333 -boundingRect.center().y() );
3334 transform.rotate( lineAngle );
3335 transform.translate( boundingRect.center().x(),
3336 boundingRect.center().y() );
3337 }
3338 else
3339 {
3340 // rotation applies around top of viewport
3341 transform.rotate( lineAngle );
3342 }
3343
3344 const QRectF transformedBounds = transform.map( points ).boundingRect();
3345
3346 // bounds are expanded out a bit to account for maximum line width
3347 const double buffer = QgsSymbolLayerUtils::estimateMaxSymbolBleed( mFillLineSymbol.get(), context.renderContext() );
3348 left = transformedBounds.left() - buffer * 2;
3349 top = transformedBounds.top() - buffer * 2;
3350 right = transformedBounds.right() + buffer * 2;
3351 bottom = transformedBounds.bottom() + buffer * 2;
3352 invertedRotateTransform = transform.inverted();
3353
3354 if ( !applyBrushTransform )
3355 {
3356 top -= transformedBounds.top() - ( outputPixelDistance * std::floor( transformedBounds.top() / outputPixelDistance ) );
3357 }
3358
3360 QgsExpressionContextScopePopper scopePopper( context.renderContext().expressionContext(), scope );
3361 const bool needsExpressionContext = mFillLineSymbol->hasDataDefinedProperties();
3362
3363 const bool prevIsSubsymbol = context.renderContext().flags() & Qgis::RenderContextFlag::RenderingSubSymbol;
3365
3366 int currentLine = 0;
3367 for ( double currentY = top; currentY <= bottom; currentY += outputPixelDistance )
3368 {
3369 if ( context.renderContext().renderingStopped() )
3370 break;
3371
3372 if ( needsExpressionContext )
3373 scope->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "symbol_line_number" ), ++currentLine, true ) );
3374
3375 double x1 = left;
3376 double y1 = currentY;
3377 double x2 = left;
3378 double y2 = currentY;
3379 invertedRotateTransform.map( left, currentY - outputPixelOffset, &x1, &y1 );
3380 invertedRotateTransform.map( right, currentY - outputPixelOffset, &x2, &y2 );
3381
3382 if ( shapeEngine )
3383 {
3384 QgsLineString ls( QgsPoint( x1, y1 ), QgsPoint( x2, y2 ) );
3385 std::unique_ptr< QgsAbstractGeometry > intersection( shapeEngine->intersection( &ls ) );
3386 for ( auto it = intersection->const_parts_begin(); it != intersection->const_parts_end(); ++it )
3387 {
3388 if ( const QgsLineString *ls = qgsgeometry_cast< const QgsLineString * >( *it ) )
3389 {
3390 mFillLineSymbol->renderPolyline( ls->asQPolygonF(), context.feature(), context.renderContext(), -1, useSelectedColor );
3391 }
3392 }
3393 }
3394 else
3395 {
3396 mFillLineSymbol->renderPolyline( QPolygonF() << QPointF( x1, y1 ) << QPointF( x2, y2 ), context.feature(), context.renderContext(), -1, useSelectedColor );
3397 }
3398 }
3399
3400 p->restore();
3401
3403}
3404
3406{
3407 QVariantMap map = QgsImageFillSymbolLayer::properties();
3408 map.insert( QStringLiteral( "angle" ), QString::number( mLineAngle ) );
3409 map.insert( QStringLiteral( "distance" ), QString::number( mDistance ) );
3410 map.insert( QStringLiteral( "line_width" ), QString::number( mLineWidth ) );
3411 map.insert( QStringLiteral( "color" ), QgsColorUtils::colorToString( mColor ) );
3412 map.insert( QStringLiteral( "offset" ), QString::number( mOffset ) );
3413 map.insert( QStringLiteral( "distance_unit" ), QgsUnitTypes::encodeUnit( mDistanceUnit ) );
3414 map.insert( QStringLiteral( "line_width_unit" ), QgsUnitTypes::encodeUnit( mLineWidthUnit ) );
3415 map.insert( QStringLiteral( "offset_unit" ), QgsUnitTypes::encodeUnit( mOffsetUnit ) );
3416 map.insert( QStringLiteral( "distance_map_unit_scale" ), QgsSymbolLayerUtils::encodeMapUnitScale( mDistanceMapUnitScale ) );
3417 map.insert( QStringLiteral( "line_width_map_unit_scale" ), QgsSymbolLayerUtils::encodeMapUnitScale( mLineWidthMapUnitScale ) );
3418 map.insert( QStringLiteral( "offset_map_unit_scale" ), QgsSymbolLayerUtils::encodeMapUnitScale( mOffsetMapUnitScale ) );
3419 map.insert( QStringLiteral( "outline_width_unit" ), QgsUnitTypes::encodeUnit( mStrokeWidthUnit ) );
3420 map.insert( QStringLiteral( "outline_width_map_unit_scale" ), QgsSymbolLayerUtils::encodeMapUnitScale( mStrokeWidthMapUnitScale ) );
3421 map.insert( QStringLiteral( "clip_mode" ), QgsSymbolLayerUtils::encodeLineClipMode( mClipMode ) );
3422 return map;
3423}
3424
3426{
3428 if ( mFillLineSymbol )
3429 {
3430 clonedLayer->setSubSymbol( mFillLineSymbol->clone() );
3431 }
3432 copyPaintEffect( clonedLayer );
3433 copyDataDefinedProperties( clonedLayer );
3434 return clonedLayer;
3435}
3436
3437void QgsLinePatternFillSymbolLayer::toSld( QDomDocument &doc, QDomElement &element, const QVariantMap &props ) const
3438{
3439 QDomElement symbolizerElem = doc.createElement( QStringLiteral( "se:PolygonSymbolizer" ) );
3440 if ( !props.value( QStringLiteral( "uom" ), QString() ).toString().isEmpty() )
3441 symbolizerElem.setAttribute( QStringLiteral( "uom" ), props.value( QStringLiteral( "uom" ), QString() ).toString() );
3442 element.appendChild( symbolizerElem );
3443
3444 // <Geometry>
3445 QgsSymbolLayerUtils::createGeometryElement( doc, symbolizerElem, props.value( QStringLiteral( "geom" ), QString() ).toString() );
3446
3447 QDomElement fillElem = doc.createElement( QStringLiteral( "se:Fill" ) );
3448 symbolizerElem.appendChild( fillElem );
3449
3450 QDomElement graphicFillElem = doc.createElement( QStringLiteral( "se:GraphicFill" ) );
3451 fillElem.appendChild( graphicFillElem );
3452
3453 QDomElement graphicElem = doc.createElement( QStringLiteral( "se:Graphic" ) );
3454 graphicFillElem.appendChild( graphicElem );
3455
3456 const QgsSldExportContext context { props.value( QStringLiteral( "SldExportContext" ), QVariant::fromValue( QgsSldExportContext() ) ).value< QgsSldExportContext >() };
3457
3458 // Export to PNG (TODO: SVG)
3459 bool exportOk { false };
3460 if ( ! context.exportFilePath().isEmpty() && context.exportOptions().testFlag( Qgis::SldExportOption::Png ) )
3461 {
3462 const QImage image { toTiledPatternImage() };
3463 if ( ! image.isNull() )
3464 {
3465 const QFileInfo info { context.exportFilePath() };
3466 QString pngPath { info.completeSuffix().isEmpty() ? context.exportFilePath() : context.exportFilePath().chopped( info.completeSuffix().length() ).append( QStringLiteral( "png" ) ) };
3467 pngPath = QgsFileUtils::uniquePath( pngPath );
3468 image.save( pngPath );
3469 QgsSymbolLayerUtils::externalGraphicToSld( doc, graphicElem, QFileInfo( pngPath ).fileName(), QStringLiteral( "image/png" ), QColor(), image.height() );
3470 exportOk = true;
3471 }
3472 }
3473
3474 if ( ! exportOk )
3475 {
3476 //line properties must be inside the graphic definition
3477 QColor lineColor = mFillLineSymbol ? mFillLineSymbol->color() : QColor();
3478 double lineWidth = mFillLineSymbol ? mFillLineSymbol->width() : 0.0;
3479 lineWidth = QgsSymbolLayerUtils::rescaleUom( lineWidth, mLineWidthUnit, props );
3480 double distance = QgsSymbolLayerUtils::rescaleUom( mDistance, mDistanceUnit, props );
3481 QgsSymbolLayerUtils::wellKnownMarkerToSld( doc, graphicElem, QStringLiteral( "horline" ), QColor(), lineColor, Qt::SolidLine, lineWidth, distance );
3482
3483 // <Rotation>
3484 QString angleFunc;
3485 bool ok;
3486 double angle = props.value( QStringLiteral( "angle" ), QStringLiteral( "0" ) ).toDouble( &ok );
3487 if ( !ok )
3488 {
3489 angleFunc = QStringLiteral( "%1 + %2" ).arg( props.value( QStringLiteral( "angle" ), QStringLiteral( "0" ) ).toString() ).arg( mLineAngle );
3490 }
3491 else if ( !qgsDoubleNear( angle + mLineAngle, 0.0 ) )
3492 {
3493 angleFunc = QString::number( angle + mLineAngle );
3494 }
3495 QgsSymbolLayerUtils::createRotationElement( doc, graphicElem, angleFunc );
3496
3497 // <se:Displacement>
3498 QPointF lineOffset( std::sin( mLineAngle ) * mOffset, std::cos( mLineAngle ) * mOffset );
3499 lineOffset = QgsSymbolLayerUtils::rescaleUom( lineOffset, mOffsetUnit, props );
3500 QgsSymbolLayerUtils::createDisplacementElement( doc, graphicElem, lineOffset );
3501 }
3502}
3503
3504QString QgsLinePatternFillSymbolLayer::ogrFeatureStyleWidth( double widthScaleFactor ) const
3505{
3506 QString featureStyle;
3507 featureStyle.append( "Brush(" );
3508 featureStyle.append( QStringLiteral( "fc:%1" ).arg( mColor.name() ) );
3509 featureStyle.append( QStringLiteral( ",bc:%1" ).arg( QLatin1String( "#00000000" ) ) ); //transparent background
3510 featureStyle.append( ",id:\"ogr-brush-2\"" );
3511 featureStyle.append( QStringLiteral( ",a:%1" ).arg( mLineAngle ) );
3512 featureStyle.append( QStringLiteral( ",s:%1" ).arg( mLineWidth * widthScaleFactor ) );
3513 featureStyle.append( ",dx:0mm" );
3514 featureStyle.append( QStringLiteral( ",dy:%1mm" ).arg( mDistance * widthScaleFactor ) );
3515 featureStyle.append( ')' );
3516 return featureStyle;
3517}
3518
3520{
3522 && ( !mFillLineSymbol || !mFillLineSymbol->hasDataDefinedProperties() ) )
3523 {
3524 return; //no data defined settings
3525 }
3526
3527 double lineAngle = mLineAngle;
3529 {
3530 context.setOriginalValueVariable( mLineAngle );
3532 }
3533 double distance = mDistance;
3535 {
3536 context.setOriginalValueVariable( mDistance );
3538 }
3539 applyPattern( context, mBrush, lineAngle, distance );
3540}
3541
3543{
3544 QString name;
3545 QColor fillColor, lineColor;
3546 double size, lineWidth;
3547 Qt::PenStyle lineStyle;
3548
3549 QDomElement fillElem = element.firstChildElement( QStringLiteral( "Fill" ) );
3550 if ( fillElem.isNull() )
3551 return nullptr;
3552
3553 QDomElement graphicFillElem = fillElem.firstChildElement( QStringLiteral( "GraphicFill" ) );
3554 if ( graphicFillElem.isNull() )
3555 return nullptr;
3556
3557 QDomElement graphicElem = graphicFillElem.firstChildElement( QStringLiteral( "Graphic" ) );
3558 if ( graphicElem.isNull() )
3559 return nullptr;
3560
3561 if ( !QgsSymbolLayerUtils::wellKnownMarkerFromSld( graphicElem, name, fillColor, lineColor, lineStyle, lineWidth, size ) )
3562 return nullptr;
3563
3564 if ( name != QLatin1String( "horline" ) )
3565 return nullptr;
3566
3567 double angle = 0.0;
3568 QString angleFunc;
3569 if ( QgsSymbolLayerUtils::rotationFromSldElement( graphicElem, angleFunc ) )
3570 {
3571 bool ok;
3572 double d = angleFunc.toDouble( &ok );
3573 if ( ok )
3574 angle = d;
3575 }
3576
3577 double offset = 0.0;
3578 QPointF vectOffset;
3579 if ( QgsSymbolLayerUtils::displacementFromSldElement( graphicElem, vectOffset ) )
3580 {
3581 offset = std::sqrt( std::pow( vectOffset.x(), 2 ) + std::pow( vectOffset.y(), 2 ) );
3582 }
3583
3584 double scaleFactor = 1.0;
3585 const QString uom = element.attribute( QStringLiteral( "uom" ) );
3586 Qgis::RenderUnit sldUnitSize = QgsSymbolLayerUtils::decodeSldUom( uom, &scaleFactor );
3587 size = size * scaleFactor;
3588 lineWidth = lineWidth * scaleFactor;
3589
3590 std::unique_ptr< QgsLinePatternFillSymbolLayer > sl = std::make_unique< QgsLinePatternFillSymbolLayer >();
3591 sl->setOutputUnit( sldUnitSize );
3592 sl->setColor( lineColor );
3593 sl->setLineWidth( lineWidth );
3594 sl->setLineAngle( angle );
3595 sl->setOffset( offset );
3596 sl->setDistance( size );
3597
3598 // try to get the stroke
3599 QDomElement strokeElem = element.firstChildElement( QStringLiteral( "Stroke" ) );
3600 if ( !strokeElem.isNull() )
3601 {
3603 if ( l )
3604 {
3605 QgsSymbolLayerList layers;
3606 layers.append( l );
3607 sl->setSubSymbol( new QgsLineSymbol( layers ) );
3608 }
3609 }
3610
3611 return sl.release();
3612}
3613
3614
3616
3619{
3620 mMarkerSymbol = std::make_unique<QgsMarkerSymbol>();
3621 QgsImageFillSymbolLayer::setSubSymbol( nullptr ); //no stroke
3622}
3623
3625
3627{
3629 mDistanceXUnit = unit;
3630 mDistanceYUnit = unit;
3631 // don't change "percentage" units -- since they adapt directly to whatever other unit is set
3633 mDisplacementXUnit = unit;
3635 mDisplacementYUnit = unit;
3637 mOffsetXUnit = unit;
3639 mOffsetYUnit = unit;
3641 mRandomDeviationXUnit = unit;
3643 mRandomDeviationYUnit = unit;
3644
3645 if ( mMarkerSymbol )
3646 {
3647 mMarkerSymbol->setOutputUnit( unit );
3648 }
3649}
3650
3667
3679
3692
3708
3710{
3711 std::unique_ptr< QgsPointPatternFillSymbolLayer > layer = std::make_unique< QgsPointPatternFillSymbolLayer >();
3712 if ( properties.contains( QStringLiteral( "distance_x" ) ) )
3713 {
3714 layer->setDistanceX( properties[QStringLiteral( "distance_x" )].toDouble() );
3715 }
3716 if ( properties.contains( QStringLiteral( "distance_y" ) ) )
3717 {
3718 layer->setDistanceY( properties[QStringLiteral( "distance_y" )].toDouble() );
3719 }
3720 if ( properties.contains( QStringLiteral( "displacement_x" ) ) )
3721 {
3722 layer->setDisplacementX( properties[QStringLiteral( "displacement_x" )].toDouble() );
3723 }
3724 if ( properties.contains( QStringLiteral( "displacement_y" ) ) )
3725 {
3726 layer->setDisplacementY( properties[QStringLiteral( "displacement_y" )].toDouble() );
3727 }
3728 if ( properties.contains( QStringLiteral( "offset_x" ) ) )
3729 {
3730 layer->setOffsetX( properties[QStringLiteral( "offset_x" )].toDouble() );
3731 }
3732 if ( properties.contains( QStringLiteral( "offset_y" ) ) )
3733 {
3734 layer->setOffsetY( properties[QStringLiteral( "offset_y" )].toDouble() );
3735 }
3736
3737 if ( properties.contains( QStringLiteral( "distance_x_unit" ) ) )
3738 {
3739 layer->setDistanceXUnit( QgsUnitTypes::decodeRenderUnit( properties[QStringLiteral( "distance_x_unit" )].toString() ) );
3740 }
3741 if ( properties.contains( QStringLiteral( "distance_x_map_unit_scale" ) ) )
3742 {
3743 layer->setDistanceXMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( properties[QStringLiteral( "distance_x_map_unit_scale" )].toString() ) );
3744 }
3745 if ( properties.contains( QStringLiteral( "distance_y_unit" ) ) )
3746 {
3747 layer->setDistanceYUnit( QgsUnitTypes::decodeRenderUnit( properties[QStringLiteral( "distance_y_unit" )].toString() ) );
3748 }
3749 if ( properties.contains( QStringLiteral( "distance_y_map_unit_scale" ) ) )
3750 {
3751 layer->setDistanceYMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( properties[QStringLiteral( "distance_y_map_unit_scale" )].toString() ) );
3752 }
3753 if ( properties.contains( QStringLiteral( "displacement_x_unit" ) ) )
3754 {
3755 layer->setDisplacementXUnit( QgsUnitTypes::decodeRenderUnit( properties[QStringLiteral( "displacement_x_unit" )].toString() ) );
3756 }
3757 if ( properties.contains( QStringLiteral( "displacement_x_map_unit_scale" ) ) )
3758 {
3759 layer->setDisplacementXMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( properties[QStringLiteral( "displacement_x_map_unit_scale" )].toString() ) );
3760 }
3761 if ( properties.contains( QStringLiteral( "displacement_y_unit" ) ) )
3762 {
3763 layer->setDisplacementYUnit( QgsUnitTypes::decodeRenderUnit( properties[QStringLiteral( "displacement_y_unit" )].toString() ) );
3764 }
3765 if ( properties.contains( QStringLiteral( "displacement_y_map_unit_scale" ) ) )
3766 {
3767 layer->setDisplacementYMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( properties[QStringLiteral( "displacement_y_map_unit_scale" )].toString() ) );
3768 }
3769 if ( properties.contains( QStringLiteral( "offset_x_unit" ) ) )
3770 {
3771 layer->setOffsetXUnit( QgsUnitTypes::decodeRenderUnit( properties[QStringLiteral( "offset_x_unit" )].toString() ) );
3772 }
3773 if ( properties.contains( QStringLiteral( "offset_x_map_unit_scale" ) ) )
3774 {
3775 layer->setOffsetXMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( properties[QStringLiteral( "offset_x_map_unit_scale" )].toString() ) );
3776 }
3777 if ( properties.contains( QStringLiteral( "offset_y_unit" ) ) )
3778 {
3779 layer->setOffsetYUnit( QgsUnitTypes::decodeRenderUnit( properties[QStringLiteral( "offset_y_unit" )].toString() ) );
3780 }
3781 if ( properties.contains( QStringLiteral( "offset_y_map_unit_scale" ) ) )
3782 {
3783 layer->setOffsetYMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( properties[QStringLiteral( "offset_y_map_unit_scale" )].toString() ) );
3784 }
3785
3786 if ( properties.contains( QStringLiteral( "random_deviation_x" ) ) )
3787 {
3788 layer->setMaximumRandomDeviationX( properties[QStringLiteral( "random_deviation_x" )].toDouble() );
3789 }
3790 if ( properties.contains( QStringLiteral( "random_deviation_y" ) ) )
3791 {
3792 layer->setMaximumRandomDeviationY( properties[QStringLiteral( "random_deviation_y" )].toDouble() );
3793 }
3794 if ( properties.contains( QStringLiteral( "random_deviation_x_unit" ) ) )
3795 {
3796 layer->setRandomDeviationXUnit( QgsUnitTypes::decodeRenderUnit( properties[QStringLiteral( "random_deviation_x_unit" )].toString() ) );
3797 }
3798 if ( properties.contains( QStringLiteral( "random_deviation_x_map_unit_scale" ) ) )
3799 {
3800 layer->setRandomDeviationXMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( properties[QStringLiteral( "random_deviation_x_map_unit_scale" )].toString() ) );
3801 }
3802 if ( properties.contains( QStringLiteral( "random_deviation_y_unit" ) ) )
3803 {
3804 layer->setRandomDeviationYUnit( QgsUnitTypes::decodeRenderUnit( properties[QStringLiteral( "random_deviation_y_unit" )].toString() ) );
3805 }
3806 if ( properties.contains( QStringLiteral( "random_deviation_y_map_unit_scale" ) ) )
3807 {
3808 layer->setRandomDeviationYMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( properties[QStringLiteral( "random_deviation_y_map_unit_scale" )].toString() ) );
3809 }
3810 unsigned long seed = 0;
3811 if ( properties.contains( QStringLiteral( "seed" ) ) )
3812 seed = properties.value( QStringLiteral( "seed" ) ).toUInt();
3813 else
3814 {
3815 // if we a creating a new point pattern fill from scratch, we default to a random seed
3816 // because seed based fills are just nicer for users vs seeing points jump around with every map refresh
3817 std::random_device rd;
3818 std::mt19937 mt( seed == 0 ? rd() : seed );
3819 std::uniform_int_distribution<> uniformDist( 1, 999999999 );
3820 seed = uniformDist( mt );
3821 }
3822 layer->setSeed( seed );
3823
3824 if ( properties.contains( QStringLiteral( "outline_width_unit" ) ) )
3825 {
3826 layer->setStrokeWidthUnit( QgsUnitTypes::decodeRenderUnit( properties[QStringLiteral( "outline_width_unit" )].toString() ) );
3827 }
3828 if ( properties.contains( QStringLiteral( "outline_width_map_unit_scale" ) ) )
3829 {
3830 layer->setStrokeWidthMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( properties[QStringLiteral( "outline_width_map_unit_scale" )].toString() ) );
3831 }
3832 if ( properties.contains( QStringLiteral( "clip_mode" ) ) )
3833 {
3834 layer->setClipMode( QgsSymbolLayerUtils::decodeMarkerClipMode( properties.value( QStringLiteral( "clip_mode" ) ).toString() ) );
3835 }
3836 if ( properties.contains( QStringLiteral( "coordinate_reference" ) ) )
3837 {
3838 layer->setCoordinateReference( QgsSymbolLayerUtils::decodeCoordinateReference( properties[QStringLiteral( "coordinate_reference" )].toString() ) );
3839 }
3840
3841 if ( properties.contains( QStringLiteral( "angle" ) ) )
3842 {
3843 layer->setAngle( properties[QStringLiteral( "angle" )].toDouble() );
3844 }
3845
3846 layer->restoreOldDataDefinedProperties( properties );
3847
3848 return layer.release();
3849}
3850
3852{
3853 return QStringLiteral( "PointPatternFill" );
3854}
3855
3856bool QgsPointPatternFillSymbolLayer::applyPattern( const QgsSymbolRenderContext &context, QBrush &brush, double distanceX, double distanceY,
3857 double displacementX, double displacementY, double offsetX, double offsetY )
3858{
3859 //render 3 rows and columns in one go to easily incorporate displacement
3860 const QgsRenderContext &ctx = context.renderContext();
3863
3864 double widthOffset = std::fmod(
3865 mOffsetXUnit == Qgis::RenderUnit::Percentage ? ( width * offsetX / 200 ) : ctx.convertToPainterUnits( offsetX, mOffsetXUnit, mOffsetXMapUnitScale ),
3866 width );
3867 double heightOffset = std::fmod(
3868 mOffsetYUnit == Qgis::RenderUnit::Percentage ? ( height * offsetY / 200 ) : ctx.convertToPainterUnits( offsetY, mOffsetYUnit, mOffsetYMapUnitScale ),
3869 height );
3870
3871 if ( width > 2000 || height > 2000 ) //protect symbol layer from eating too much memory
3872 {
3873 brush.setTextureImage( QImage() );
3874 return false;
3875 }
3876
3877 QImage patternImage( width, height, QImage::Format_ARGB32 );
3878 patternImage.fill( 0 );
3879 if ( patternImage.isNull() )
3880 {
3881 brush.setTextureImage( QImage() );
3882 return false;
3883 }
3884 if ( mMarkerSymbol )
3885 {
3886 QPainter p( &patternImage );
3887
3888 //marker rendering needs context for drawing on patternImage
3889 QgsRenderContext pointRenderContext;
3890 pointRenderContext.setRendererScale( context.renderContext().rendererScale() );
3891 pointRenderContext.setPainter( &p );
3892 pointRenderContext.setScaleFactor( context.renderContext().scaleFactor() );
3893
3896 pointRenderContext.setMapToPixel( mtp );
3897 pointRenderContext.setForceVectorOutput( false );
3898 pointRenderContext.setExpressionContext( context.renderContext().expressionContext() );
3900
3902 mMarkerSymbol->startRender( pointRenderContext, context.fields() );
3903
3904 //render points on distance grid
3905 for ( double currentX = -width; currentX <= width * 2.0; currentX += width )
3906 {
3907 for ( double currentY = -height; currentY <= height * 2.0; currentY += height )
3908 {
3909 mMarkerSymbol->renderPoint( QPointF( currentX + widthOffset, currentY + heightOffset ), context.feature(), pointRenderContext );
3910 }
3911 }
3912
3913 //render displaced points
3914 double displacementPixelX = mDisplacementXUnit == Qgis::RenderUnit::Percentage
3915 ? ( width * displacementX / 200 )
3916 : ctx.convertToPainterUnits( displacementX, mDisplacementXUnit, mDisplacementXMapUnitScale );
3917 double displacementPixelY = mDisplacementYUnit == Qgis::RenderUnit::Percentage
3918 ? ( height * displacementY / 200 )
3919 : ctx.convertToPainterUnits( displacementY, mDisplacementYUnit, mDisplacementYMapUnitScale );
3920 for ( double currentX = -width; currentX <= width * 2.0; currentX += width )
3921 {
3922 for ( double currentY = -height / 2.0; currentY <= height * 2.0; currentY += height )
3923 {
3924 mMarkerSymbol->renderPoint( QPointF( currentX + widthOffset + displacementPixelX, currentY + heightOffset ), context.feature(), pointRenderContext );
3925 }
3926 }
3927
3928 for ( double currentX = -width / 2.0; currentX <= width * 2.0; currentX += width )
3929 {
3930 for ( double currentY = -height; currentY <= height * 2.0; currentY += height / 2.0 )
3931 {
3932 mMarkerSymbol->renderPoint( QPointF( currentX + widthOffset + ( std::fmod( currentY, height ) != 0 ? displacementPixelX : 0 ), currentY + heightOffset - displacementPixelY ), context.feature(), pointRenderContext );
3933 }
3934 }
3935
3936 mMarkerSymbol->stopRender( pointRenderContext );
3937 }
3938
3939 if ( !qgsDoubleNear( context.opacity(), 1.0 ) )
3940 {
3941 QImage transparentImage = patternImage.copy();
3942 QgsSymbolLayerUtils::multiplyImageOpacity( &transparentImage, context.opacity() );
3943 brush.setTextureImage( transparentImage );
3944 }
3945 else
3946 {
3947 brush.setTextureImage( patternImage );
3948 }
3949 QTransform brushTransform;
3950 brush.setTransform( brushTransform );
3951
3952 return true;
3953}
3954
3956{
3957 // if we are using a vector based output, we need to render points as vectors
3958 // (OR if the marker has data defined symbology, in which case we need to evaluate this point-by-point)
3959 mRenderUsingMarkers = context.forceVectorRendering()
3960 || ( mMarkerSymbol && mMarkerSymbol->hasDataDefinedProperties() )
3964 || mClipMode != Qgis::MarkerClipMode::Shape
3967 || !qgsDoubleNear( mAngle, 0 )
3969
3970 if ( !mRenderUsingMarkers )
3971 {
3972 // optimised render for screen only, use image based brush
3973 // (fallback to line rendering when pattern image will result in too large a memory footprint)
3974 mRenderUsingMarkers = !applyPattern( context, mBrush, mDistanceX, mDistanceY, mDisplacementX, mDisplacementY, mOffsetX, mOffsetY );
3975 }
3976
3977 if ( mRenderUsingMarkers && mMarkerSymbol )
3978 {
3980 mMarkerSymbol->startRender( context.renderContext(), context.fields() );
3982 }
3983}
3984
3986{
3988 {
3989 mMarkerSymbol->stopRender( context.renderContext() );
3991 }
3992}
3993
3995{
3996 installMasks( context, true );
3997
3998 // The base class version passes this on to the subsymbol, but we deliberately don't do that here.
3999 // Otherwise generators used in the subsymbol will only render a single point per feature (they
4000 // have logic to only render once per paired call to startFeatureRender/stopFeatureRender).
4001}
4002
4004{
4005 removeMasks( context, true );
4006
4007 // The base class version passes this on to the subsymbol, but we deliberately don't do that here.
4008 // Otherwise generators used in the subsymbol will only render a single point per feature (they
4009 // have logic to only render once per paired call to startFeatureRender/stopFeatureRender).
4010}
4011
4012void QgsPointPatternFillSymbolLayer::renderPolygon( const QPolygonF &points, const QVector<QPolygonF> *rings, QgsSymbolRenderContext &context )
4013{
4014 const bool useSelectedColor = shouldRenderUsingSelectionColor( context );
4015 if ( !useSelectedColor && !mRenderUsingMarkers )
4016 {
4017 // use image based brush for speed
4018 QgsImageFillSymbolLayer::renderPolygon( points, rings, context );
4019 return;
4020 }
4021
4023 {
4025 mMarkerSymbol->startRender( context.renderContext(), context.fields() );
4027 }
4028
4029 // vector based output - so draw dot by dot!
4030 QPainter *p = context.renderContext().painter();
4031 if ( !p )
4032 {
4033 return;
4034 }
4035
4036 double angle = mAngle;
4038 {
4041 }
4042
4043 double distanceX = mDistanceX;
4045 {
4048 }
4050
4051 double distanceY = mDistanceY;
4053 {
4056 }
4058
4059 double offsetX = mOffsetX;
4061 {
4064 }
4065 const double widthOffset = std::fmod(
4067 ? ( offsetX * width / 100 )
4069 width );
4070
4071 double offsetY = mOffsetY;
4073 {
4076 }
4077 const double heightOffset = std::fmod(
4079 ? ( offsetY * height / 100 )
4081 height );
4082
4085 {
4088 }
4089 const double displacementPixelX = mDisplacementXUnit == Qgis::RenderUnit::Percentage
4090 ? ( displacementX * width / 100 )
4092
4095 {
4098 }
4099 const double displacementPixelY = mDisplacementYUnit == Qgis::RenderUnit::Percentage
4100 ? ( displacementY * height / 100 )
4102
4103 p->setPen( QPen( Qt::NoPen ) );
4104
4105 // if invalid parameters, skip out
4106 if ( qgsDoubleNear( width, 0 ) || qgsDoubleNear( height, 0 ) || width < 0 || height < 0 )
4107 return;
4108
4109 p->save();
4110
4111 Qgis::MarkerClipMode clipMode = mClipMode;
4113 {
4115 bool ok = false;
4116 const QString valueString = mDataDefinedProperties.valueAsString( QgsSymbolLayer::Property::MarkerClipping, context.renderContext().expressionContext(), QString(), &ok );
4117 if ( ok )
4118 {
4119 Qgis::MarkerClipMode decodedMode = QgsSymbolLayerUtils::decodeMarkerClipMode( valueString, &ok );
4120 if ( ok )
4121 clipMode = decodedMode;
4122 }
4123 }
4124
4125 std::unique_ptr< QgsPolygon > shapePolygon;
4126 std::unique_ptr< QgsGeometryEngine > shapeEngine;
4127 switch ( clipMode )
4128 {
4132 {
4133 shapePolygon = std::make_unique< QgsPolygon >();
4134 shapePolygon->setExteriorRing( QgsLineString::fromQPolygonF( points ) );
4135 if ( rings )
4136 {
4137 for ( const QPolygonF &ring : *rings )
4138 {
4139 shapePolygon->addInteriorRing( QgsLineString::fromQPolygonF( ring ) );
4140 }
4141 }
4142 shapeEngine.reset( QgsGeometry::createGeometryEngine( shapePolygon.get() ) );
4143 shapeEngine->prepareGeometry();
4144 break;
4145 }
4146
4148 {
4149 QPainterPath path;
4150 path.addPolygon( points );
4151 if ( rings )
4152 {
4153 for ( const QPolygonF &ring : *rings )
4154 {
4155 path.addPolygon( ring );
4156 }
4157 }
4158 p->setClipPath( path, Qt::IntersectClip );
4159 break;
4160 }
4161 }
4162
4163 const bool applyBrushTransform = applyBrushTransformFromContext( &context );
4164 const QRectF boundingRect = points.boundingRect();
4165
4166 QTransform invertedRotateTransform;
4167 double left;
4168 double top;
4169 double right;
4170 double bottom;
4171
4172 if ( !qgsDoubleNear( angle, 0 ) )
4173 {
4174 QTransform transform;
4175 if ( applyBrushTransform )
4176 {
4177 // rotation applies around center of feature
4178 transform.translate( -boundingRect.center().x(),
4179 -boundingRect.center().y() );
4180 transform.rotate( -angle );
4181 transform.translate( boundingRect.center().x(),
4182 boundingRect.center().y() );
4183 }
4184 else
4185 {
4186 // rotation applies around top of viewport
4187 transform.rotate( -angle );
4188 }
4189
4190 const QRectF transformedBounds = transform.map( points ).boundingRect();
4191 left = transformedBounds.left() - 2 * width;
4192 top = transformedBounds.top() - 2 * height;
4193 right = transformedBounds.right() + 2 * width;
4194 bottom = transformedBounds.bottom() + 2 * height;
4195 invertedRotateTransform = transform.inverted();
4196
4197 if ( !applyBrushTransform )
4198 {
4199 left -= transformedBounds.left() - ( width * std::floor( transformedBounds.left() / width ) );
4200 top -= transformedBounds.top() - ( height * std::floor( transformedBounds.top() / height ) );
4201 }
4202 }
4203 else
4204 {
4205 left = boundingRect.left() - 2 * width;
4206 top = boundingRect.top() - 2 * height;
4207 right = boundingRect.right() + 2 * width;
4208 bottom = boundingRect.bottom() + 2 * height;
4209
4210 if ( !applyBrushTransform )
4211 {
4212 left -= boundingRect.left() - ( width * std::floor( boundingRect.left() / width ) );
4213 top -= boundingRect.top() - ( height * std::floor( boundingRect.top() / height ) );
4214 }
4215 }
4216
4217 unsigned long seed = mSeed;
4219 {
4220 context.renderContext().expressionContext().setOriginalValueVariable( static_cast< unsigned long long >( seed ) );
4222 }
4223
4224 double maxRandomDeviationX = mRandomDeviationX;
4226 {
4227 context.setOriginalValueVariable( maxRandomDeviationX );
4228 maxRandomDeviationX = mDataDefinedProperties.valueAsDouble( QgsSymbolLayer::Property::RandomOffsetX, context.renderContext().expressionContext(), maxRandomDeviationX );
4229 }
4230 const double maxRandomDeviationPixelX = mRandomDeviationXUnit == Qgis::RenderUnit::Percentage ? ( maxRandomDeviationX * width / 100 )
4232
4233 double maxRandomDeviationY = mRandomDeviationY;
4235 {
4236 context.setOriginalValueVariable( maxRandomDeviationY );
4237 maxRandomDeviationY = mDataDefinedProperties.valueAsDouble( QgsSymbolLayer::Property::RandomOffsetY, context.renderContext().expressionContext(), maxRandomDeviationY );
4238 }
4239 const double maxRandomDeviationPixelY = mRandomDeviationYUnit == Qgis::RenderUnit::Percentage ? ( maxRandomDeviationY * height / 100 )
4241
4242 std::random_device rd;
4243 std::mt19937 mt( seed == 0 ? rd() : seed );
4244 std::uniform_real_distribution<> uniformDist( 0, 1 );
4245 const bool useRandomShift = !qgsDoubleNear( maxRandomDeviationPixelX, 0 ) || !qgsDoubleNear( maxRandomDeviationPixelY, 0 );
4246
4248 QgsExpressionContextScopePopper scopePopper( context.renderContext().expressionContext(), scope );
4249 int pointNum = 0;
4250 const bool needsExpressionContext = mMarkerSymbol->hasDataDefinedProperties();
4251
4252 const bool prevIsSubsymbol = context.renderContext().flags() & Qgis::RenderContextFlag::RenderingSubSymbol;
4254
4255 const double prevOpacity = mMarkerSymbol->opacity();
4256 mMarkerSymbol->setOpacity( mMarkerSymbol->opacity() * context.opacity() );
4257
4258 bool alternateColumn = false;
4259 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
4260 for ( double currentX = left; currentX <= right; currentX += width, alternateColumn = !alternateColumn )
4261 {
4262 if ( context.renderContext().renderingStopped() )
4263 break;
4264
4265 if ( needsExpressionContext )
4266 scope->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "symbol_marker_column" ), ++currentCol, true ) );
4267
4268 bool alternateRow = false;
4269 const double columnX = currentX + widthOffset;
4270 int currentRow = -3;
4271 for ( double currentY = top; currentY <= bottom; currentY += height, alternateRow = !alternateRow )
4272 {
4273 if ( context.renderContext().renderingStopped() )
4274 break;
4275
4276 double y = currentY + heightOffset;
4277 double x = columnX;
4278 if ( alternateRow )
4279 x += displacementPixelX;
4280
4281 if ( !alternateColumn )
4282 y -= displacementPixelY;
4283
4284 if ( !qgsDoubleNear( angle, 0 ) )
4285 {
4286 double xx = x;
4287 double yy = y;
4288 invertedRotateTransform.map( xx, yy, &x, &y );
4289 }
4290
4291 if ( useRandomShift )
4292 {
4293 x += ( 2 * uniformDist( mt ) - 1 ) * maxRandomDeviationPixelX;
4294 y += ( 2 * uniformDist( mt ) - 1 ) * maxRandomDeviationPixelY;
4295 }
4296
4297 if ( needsExpressionContext )
4298 {
4300 scope->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "symbol_marker_row" ), ++currentRow, true ) );
4301 }
4302
4303 if ( shapeEngine )
4304 {
4305 bool renderPoint = true;
4306 switch ( clipMode )
4307 {
4309 {
4310 // 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
4311 const QgsRectangle markerRect = QgsRectangle( mMarkerSymbol->bounds( QPointF( x, y ), context.renderContext(), context.feature() ? *context.feature() : QgsFeature() ) );
4312 QgsPoint p( markerRect.center() );
4313 renderPoint = shapeEngine->intersects( &p );
4314 break;
4315 }
4316
4319 {
4320 const QgsGeometry markerBounds = QgsGeometry::fromRect( QgsRectangle( mMarkerSymbol->bounds( QPointF( x, y ), context.renderContext(), context.feature() ? *context.feature() : QgsFeature() ) ) );
4321
4323 renderPoint = shapeEngine->contains( markerBounds.constGet() );
4324 else
4325 renderPoint = shapeEngine->intersects( markerBounds.constGet() );
4326 break;
4327 }
4328
4330 break;
4331 }
4332
4333 if ( !renderPoint )
4334 continue;
4335 }
4336
4337 mMarkerSymbol->renderPoint( QPointF( x, y ), context.feature(), context.renderContext(), -1, useSelectedColor );
4338 }
4339 }
4340
4341 mMarkerSymbol->setOpacity( prevOpacity );
4342
4343 p->restore();
4344
4346}
4347
4349{
4350 QVariantMap map = QgsImageFillSymbolLayer::properties();
4351 map.insert( QStringLiteral( "distance_x" ), QString::number( mDistanceX ) );
4352 map.insert( QStringLiteral( "distance_y" ), QString::number( mDistanceY ) );
4353 map.insert( QStringLiteral( "displacement_x" ), QString::number( mDisplacementX ) );
4354 map.insert( QStringLiteral( "displacement_y" ), QString::number( mDisplacementY ) );
4355 map.insert( QStringLiteral( "offset_x" ), QString::number( mOffsetX ) );
4356 map.insert( QStringLiteral( "offset_y" ), QString::number( mOffsetY ) );
4357 map.insert( QStringLiteral( "distance_x_unit" ), QgsUnitTypes::encodeUnit( mDistanceXUnit ) );
4358 map.insert( QStringLiteral( "distance_y_unit" ), QgsUnitTypes::encodeUnit( mDistanceYUnit ) );
4359 map.insert( QStringLiteral( "displacement_x_unit" ), QgsUnitTypes::encodeUnit( mDisplacementXUnit ) );
4360 map.insert( QStringLiteral( "displacement_y_unit" ), QgsUnitTypes::encodeUnit( mDisplacementYUnit ) );
4361 map.insert( QStringLiteral( "offset_x_unit" ), QgsUnitTypes::encodeUnit( mOffsetXUnit ) );
4362 map.insert( QStringLiteral( "offset_y_unit" ), QgsUnitTypes::encodeUnit( mOffsetYUnit ) );
4363 map.insert( QStringLiteral( "distance_x_map_unit_scale" ), QgsSymbolLayerUtils::encodeMapUnitScale( mDistanceXMapUnitScale ) );
4364 map.insert( QStringLiteral( "distance_y_map_unit_scale" ), QgsSymbolLayerUtils::encodeMapUnitScale( mDistanceYMapUnitScale ) );
4365 map.insert( QStringLiteral( "displacement_x_map_unit_scale" ), QgsSymbolLayerUtils::encodeMapUnitScale( mDisplacementXMapUnitScale ) );
4366 map.insert( QStringLiteral( "displacement_y_map_unit_scale" ), QgsSymbolLayerUtils::encodeMapUnitScale( mDisplacementYMapUnitScale ) );
4367 map.insert( QStringLiteral( "offset_x_map_unit_scale" ), QgsSymbolLayerUtils::encodeMapUnitScale( mOffsetXMapUnitScale ) );
4368 map.insert( QStringLiteral( "offset_y_map_unit_scale" ), QgsSymbolLayerUtils::encodeMapUnitScale( mOffsetYMapUnitScale ) );
4369 map.insert( QStringLiteral( "outline_width_unit" ), QgsUnitTypes::encodeUnit( mStrokeWidthUnit ) );
4370 map.insert( QStringLiteral( "outline_width_map_unit_scale" ), QgsSymbolLayerUtils::encodeMapUnitScale( mStrokeWidthMapUnitScale ) );
4371 map.insert( QStringLiteral( "clip_mode" ), QgsSymbolLayerUtils::encodeMarkerClipMode( mClipMode ) );
4372 map.insert( QStringLiteral( "random_deviation_x" ), QString::number( mRandomDeviationX ) );
4373 map.insert( QStringLiteral( "random_deviation_y" ), QString::number( mRandomDeviationY ) );
4374 map.insert( QStringLiteral( "random_deviation_x_unit" ), QgsUnitTypes::encodeUnit( mRandomDeviationXUnit ) );
4375 map.insert( QStringLiteral( "random_deviation_y_unit" ), QgsUnitTypes::encodeUnit( mRandomDeviationYUnit ) );
4376 map.insert( QStringLiteral( "random_deviation_x_map_unit_scale" ), QgsSymbolLayerUtils::encodeMapUnitScale( mRandomDeviationXMapUnitScale ) );
4377 map.insert( QStringLiteral( "random_deviation_y_map_unit_scale" ), QgsSymbolLayerUtils::encodeMapUnitScale( mRandomDeviationYMapUnitScale ) );
4378 map.insert( QStringLiteral( "seed" ), QString::number( mSeed ) );
4379 map.insert( QStringLiteral( "angle" ), mAngle );
4380 return map;
4381}
4382
4384{
4386 if ( mMarkerSymbol )
4387 {
4388 clonedLayer->setSubSymbol( mMarkerSymbol->clone() );
4389 }
4390 clonedLayer->setClipMode( mClipMode );
4391 copyDataDefinedProperties( clonedLayer );
4392 copyPaintEffect( clonedLayer );
4393 return clonedLayer;
4394}
4395
4396void QgsPointPatternFillSymbolLayer::toSld( QDomDocument &doc, QDomElement &element, const QVariantMap &props ) const
4397{
4398 for ( int symbolLayerIdx = 0; symbolLayerIdx < mMarkerSymbol->symbolLayerCount(); symbolLayerIdx++ )
4399 {
4400 QDomElement symbolizerElem = doc.createElement( QStringLiteral( "se:PolygonSymbolizer" ) );
4401 if ( !props.value( QStringLiteral( "uom" ), QString() ).toString().isEmpty() )
4402 symbolizerElem.setAttribute( QStringLiteral( "uom" ), props.value( QStringLiteral( "uom" ), QString() ).toString() );
4403 element.appendChild( symbolizerElem );
4404
4405 // <Geometry>
4406 QgsSymbolLayerUtils::createGeometryElement( doc, symbolizerElem, props.value( QStringLiteral( "geom" ), QString() ).toString() );
4407
4408 QDomElement fillElem = doc.createElement( QStringLiteral( "se:Fill" ) );
4409 symbolizerElem.appendChild( fillElem );
4410
4411 QDomElement graphicFillElem = doc.createElement( QStringLiteral( "se:GraphicFill" ) );
4412 fillElem.appendChild( graphicFillElem );
4413
4414 QgsSymbolLayer *layer = mMarkerSymbol->symbolLayer( symbolLayerIdx );
4415
4416 const QgsSldExportContext context { props.value( QStringLiteral( "SldExportContext" ), QVariant::fromValue( QgsSldExportContext() ) ).value< QgsSldExportContext >() };
4417
4418 // Export to PNG (TODO: SVG)
4419 bool exportOk { false };
4420 if ( ! context.exportFilePath().isEmpty() && context.exportOptions().testFlag( Qgis::SldExportOption::Png ) )
4421 {
4422 const QImage image { toTiledPatternImage( ) };
4423 if ( ! image.isNull() )
4424 {
4425 QDomElement graphicElem = doc.createElement( QStringLiteral( "se:Graphic" ) );
4426 graphicFillElem.appendChild( graphicElem );
4427 const QFileInfo info { context.exportFilePath() };
4428 QString pngPath { info.completeSuffix().isEmpty() ? context.exportFilePath() : context.exportFilePath().chopped( info.completeSuffix().length() ).append( QStringLiteral( "png" ) ) };
4429 pngPath = QgsFileUtils::uniquePath( pngPath );
4430 image.save( pngPath );
4431 QgsSymbolLayerUtils::externalGraphicToSld( doc, graphicElem, QFileInfo( pngPath ).fileName(), QStringLiteral( "image/png" ), QColor(), image.height() );
4432 exportOk = true;
4433 }
4434 }
4435
4436 if ( ! exportOk )
4437 {
4438 // Converts to GeoServer "graphic-margin": symbol size must be subtracted from distance and then divided by 2
4439 const double markerSize { mMarkerSymbol->size() };
4440
4441 // store distanceX, distanceY, displacementX, displacementY in a <VendorOption>
4444 // From: https://docs.geoserver.org/stable/en/user/styling/sld/extensions/margins.html
4445 // top-bottom,right-left (two values, top and bottom sharing the same value)
4446 const QString marginSpec = QString( "%1 %2" ).arg( qgsDoubleToString( ( dy - markerSize ) / 2, 2 ), qgsDoubleToString( ( dx - markerSize ) / 2, 2 ) );
4447
4448 QDomElement graphicMarginElem = QgsSymbolLayerUtils::createVendorOptionElement( doc, QStringLiteral( "graphic-margin" ), marginSpec );
4449 symbolizerElem.appendChild( graphicMarginElem );
4450
4451 if ( QgsMarkerSymbolLayer *markerLayer = dynamic_cast<QgsMarkerSymbolLayer *>( layer ) )
4452 {
4453 markerLayer->writeSldMarker( doc, graphicFillElem, props );
4454 }
4455 else if ( layer )
4456 {
4457 QString errorMsg = QStringLiteral( "QgsMarkerSymbolLayer expected, %1 found. Skip it." ).arg( layer->layerType() );
4458 graphicFillElem.appendChild( doc.createComment( errorMsg ) );
4459 }
4460 else
4461 {
4462 QString errorMsg = QStringLiteral( "Missing point pattern symbol layer. Skip it." );
4463 graphicFillElem.appendChild( doc.createComment( errorMsg ) );
4464 }
4465 }
4466 }
4467}
4468
4470{
4471
4472 double angleRads { qDegreesToRadians( mAngle ) };
4473
4474 int distanceXPx { static_cast<int>( QgsSymbolLayerUtils::rescaleUom( mDistanceX, mDistanceXUnit, {} ) ) };
4475 int distanceYPx { static_cast<int>( QgsSymbolLayerUtils::rescaleUom( mDistanceY, mDistanceYUnit, {} ) ) };
4476
4477 const int displacementXPx { static_cast<int>( QgsSymbolLayerUtils::rescaleUom( mDisplacementX, mDisplacementXUnit, {} ) ) };
4478 const int displacementYPx { static_cast<int>( QgsSymbolLayerUtils::rescaleUom( mDisplacementY, mDisplacementYUnit, {} ) ) };
4479
4480 // Consider displacement, double the distance.
4481 if ( displacementXPx != 0 )
4482 {
4483 distanceXPx *= 2;
4484 }
4485
4486 if ( displacementYPx != 0 )
4487 {
4488 distanceYPx *= 2;
4489 }
4490
4491 const QSize size { QgsSymbolLayerUtils::tileSize( distanceXPx, distanceYPx, angleRads ) };
4492
4493 QPixmap pixmap( size );
4494 pixmap.fill( Qt::transparent );
4495 QPainter painter;
4496 painter.begin( &pixmap );
4497 painter.setRenderHint( QPainter::Antialiasing );
4498 QgsRenderContext renderContext = QgsRenderContext::fromQPainter( &painter );
4502 renderContext.setForceVectorOutput( true );
4503 QgsSymbolRenderContext symbolContext( renderContext, Qgis::RenderUnit::Pixels, 1.0, false, Qgis::SymbolRenderHints() );
4504
4505 std::unique_ptr< QgsPointPatternFillSymbolLayer > layerClone( clone() );
4506
4507 layerClone->setAngle( qRadiansToDegrees( angleRads ) );
4508
4509 // No way we can export a random pattern, disable it.
4510 layerClone->setMaximumRandomDeviationX( 0 );
4511 layerClone->setMaximumRandomDeviationY( 0 );
4512
4513 layerClone->drawPreviewIcon( symbolContext, pixmap.size() );
4514 painter.end();
4515 return pixmap.toImage();
4516}
4517
4519{
4520
4521 // input element is PolygonSymbolizer
4522
4523 QDomElement fillElem = element.firstChildElement( QStringLiteral( "Fill" ) );
4524 if ( fillElem.isNull() )
4525 return nullptr;
4526
4527 QDomElement graphicFillElem = fillElem.firstChildElement( QStringLiteral( "GraphicFill" ) );
4528 if ( graphicFillElem.isNull() )
4529 return nullptr;
4530
4531 QDomElement graphicElem = graphicFillElem.firstChildElement( QStringLiteral( "Graphic" ) );
4532 if ( graphicElem.isNull() )
4533 return nullptr;
4534
4535 QgsSymbolLayer *simpleMarkerSl = QgsSymbolLayerUtils::createMarkerLayerFromSld( graphicFillElem );
4536 if ( !simpleMarkerSl )
4537 return nullptr;
4538
4539
4540 QgsSymbolLayerList layers;
4541 layers.append( simpleMarkerSl );
4542
4543 std::unique_ptr< QgsMarkerSymbol > marker = std::make_unique< QgsMarkerSymbol >( layers );
4544
4545 // Converts from GeoServer "graphic-margin": symbol size must be added and margin doubled
4546 const double markerSize { marker->size() };
4547
4548 std::unique_ptr< QgsPointPatternFillSymbolLayer > pointPatternFillSl = std::make_unique< QgsPointPatternFillSymbolLayer >();
4549 pointPatternFillSl->setSubSymbol( marker.release() );
4550 // This may not be correct in all cases, TODO: check "uom"
4551 pointPatternFillSl->setDistanceXUnit( Qgis::RenderUnit::Pixels );
4552 pointPatternFillSl->setDistanceYUnit( Qgis::RenderUnit::Pixels );
4553
4554 auto distanceParser = [ & ]( const QStringList & values )
4555 {
4556 switch ( values.count( ) )
4557 {
4558 case 1: // top-right-bottom-left (single value for all four margins)
4559 {
4560 bool ok;
4561 const double v { values.at( 0 ).toDouble( &ok ) };
4562 if ( ok )
4563 {
4564 pointPatternFillSl->setDistanceX( v * 2 + markerSize );
4565 pointPatternFillSl->setDistanceY( v * 2 + markerSize );
4566 }
4567 break;
4568 }
4569 case 2: // top-bottom,right-left (two values, top and bottom sharing the same value)
4570 {
4571 bool ok;
4572 const double vX { values.at( 1 ).toDouble( &ok ) };
4573 if ( ok )
4574 {
4575 pointPatternFillSl->setDistanceX( vX * 2 + markerSize );
4576 }
4577 const double vY { values.at( 0 ).toDouble( &ok ) };
4578 if ( ok )
4579 {
4580 pointPatternFillSl->setDistanceY( vY * 2 + markerSize );
4581 }
4582 break;
4583 }
4584 case 3: // top,right-left,bottom (three values, with right and left sharing the same value)
4585 {
4586 bool ok;
4587 const double vX { values.at( 1 ).toDouble( &ok ) };
4588 if ( ok )
4589 {
4590 pointPatternFillSl->setDistanceX( vX * 2 + markerSize );
4591 }
4592 const double vYt { values.at( 0 ).toDouble( &ok ) };
4593 if ( ok )
4594 {
4595 const double vYb { values.at( 2 ).toDouble( &ok ) };
4596 if ( ok )
4597 {
4598 pointPatternFillSl->setDistanceY( ( vYt + vYb ) + markerSize );
4599 }
4600 }
4601 break;
4602 }
4603 case 4: // top,right,bottom,left (one explicit value per margin)
4604 {
4605 bool ok;
4606 const double vYt { values.at( 0 ).toDouble( &ok ) };
4607 if ( ok )
4608 {
4609 const double vYb { values.at( 2 ).toDouble( &ok ) };
4610 if ( ok )
4611 {
4612 pointPatternFillSl->setDistanceY( ( vYt + vYb ) + markerSize );
4613 }
4614 }
4615 const double vXr { values.at( 1 ).toDouble( &ok ) };
4616 if ( ok )
4617 {
4618 const double vXl { values.at( 3 ).toDouble( &ok ) };
4619 if ( ok )
4620 {
4621 pointPatternFillSl->setDistanceX( ( vXr + vXl ) + markerSize );
4622 }
4623 }
4624 break;
4625 }
4626 default:
4627 break;
4628 }
4629 };
4630
4631 // Set distance X and Y from vendor options, or from Size if no vendor options are set
4632 bool distanceFromVendorOption { false };
4633 QgsStringMap vendorOptions = QgsSymbolLayerUtils::getVendorOptionList( element );
4634 for ( QgsStringMap::iterator it = vendorOptions.begin(); it != vendorOptions.end(); ++it )
4635 {
4636 // Legacy
4637 if ( it.key() == QLatin1String( "distance" ) )
4638 {
4639 distanceParser( it.value().split( ',' ) );
4640 distanceFromVendorOption = true;
4641 }
4642 // GeoServer
4643 else if ( it.key() == QLatin1String( "graphic-margin" ) )
4644 {
4645 distanceParser( it.value().split( ' ' ) );
4646 distanceFromVendorOption = true;
4647 }
4648 }
4649
4650 // Get distances from size
4651 if ( ! distanceFromVendorOption && ! graphicFillElem.elementsByTagName( QStringLiteral( "Size" ) ).isEmpty() )
4652 {
4653 const QDomElement sizeElement { graphicFillElem.elementsByTagName( QStringLiteral( "Size" ) ).at( 0 ).toElement() };
4654 bool ok;
4655 const double size { sizeElement.text().toDouble( &ok ) };
4656 if ( ok )
4657 {
4658 pointPatternFillSl->setDistanceX( size );
4659 pointPatternFillSl->setDistanceY( size );
4660 }
4661 }
4662
4663 return pointPatternFillSl.release();
4664}
4665
4667{
4668 if ( !symbol )
4669 {
4670 return false;
4671 }
4672
4673 if ( symbol->type() == Qgis::SymbolType::Marker )
4674 {
4675 QgsMarkerSymbol *markerSymbol = static_cast<QgsMarkerSymbol *>( symbol );
4676 mMarkerSymbol.reset( markerSymbol );
4677 }
4678 return true;
4679}
4680
4685
4687{
4691 && ( !mMarkerSymbol || !mMarkerSymbol->hasDataDefinedProperties() ) )
4692 {
4693 return;
4694 }
4695
4696 double distanceX = mDistanceX;
4698 {
4701 }
4702 double distanceY = mDistanceY;
4704 {
4707 }
4710 {
4713 }
4716 {
4719 }
4720 double offsetX = mOffsetX;
4722 {
4725 }
4726 double offsetY = mOffsetY;
4728 {
4731 }
4732 applyPattern( context, mBrush, distanceX, distanceY, displacementX, displacementY, offsetX, offsetY );
4733}
4734
4736{
4737 return 0;
4738}
4739
4741{
4742 QSet<QString> attributes = QgsImageFillSymbolLayer::usedAttributes( context );
4743
4744 if ( mMarkerSymbol )
4745 attributes.unite( mMarkerSymbol->usedAttributes( context ) );
4746
4747 return attributes;
4748}
4749
4751{
4753 return true;
4754 if ( mMarkerSymbol && mMarkerSymbol->hasDataDefinedProperties() )
4755 return true;
4756 return false;
4757}
4758
4760{
4761 mColor = c;
4762 if ( mMarkerSymbol )
4763 mMarkerSymbol->setColor( c );
4764}
4765
4767{
4768 return mMarkerSymbol ? mMarkerSymbol->color() : mColor;
4769}
4770
4772
4773
4778
4780
4782{
4783 std::unique_ptr< QgsCentroidFillSymbolLayer > sl = std::make_unique< QgsCentroidFillSymbolLayer >();
4784
4785 if ( properties.contains( QStringLiteral( "point_on_surface" ) ) )
4786 sl->setPointOnSurface( properties[QStringLiteral( "point_on_surface" )].toInt() != 0 );
4787 if ( properties.contains( QStringLiteral( "point_on_all_parts" ) ) )
4788 sl->setPointOnAllParts( properties[QStringLiteral( "point_on_all_parts" )].toInt() != 0 );
4789 if ( properties.contains( QStringLiteral( "clip_points" ) ) )
4790 sl->setClipPoints( properties[QStringLiteral( "clip_points" )].toInt() != 0 );
4791 if ( properties.contains( QStringLiteral( "clip_on_current_part_only" ) ) )
4792 sl->setClipOnCurrentPartOnly( properties[QStringLiteral( "clip_on_current_part_only" )].toInt() != 0 );
4793
4794 sl->restoreOldDataDefinedProperties( properties );
4795
4796 return sl.release();
4797}
4798
4800{
4801 return QStringLiteral( "CentroidFill" );
4802}
4803
4804void QgsCentroidFillSymbolLayer::setColor( const QColor &color )
4805{
4806 mMarker->setColor( color );
4807 mColor = color;
4808}
4809
4811{
4812 return mMarker ? mMarker->color() : mColor;
4813}
4814
4816{
4817 mMarker->setRenderHints( mMarker->renderHints() | Qgis::SymbolRenderHint::IsSymbolLayerSubSymbol );
4818 mMarker->startRender( context.renderContext(), context.fields() );
4819}
4820
4822{
4823 mMarker->stopRender( context.renderContext() );
4824}
4825
4826void QgsCentroidFillSymbolLayer::renderPolygon( const QPolygonF &points, const QVector<QPolygonF> *rings, QgsSymbolRenderContext &context )
4827{
4828 Part part;
4829 part.exterior = points;
4830 if ( rings )
4831 part.rings = *rings;
4832
4833 if ( mRenderingFeature )
4834 {
4835 // in the middle of rendering a possibly multi-part feature, so we collect all the parts and defer the actual rendering
4836 // until after we've received the final part
4837 mFeatureSymbolOpacity = context.opacity();
4839 mCurrentParts << part;
4840 }
4841 else
4842 {
4843 // not rendering a feature, so we can just render the polygon immediately
4844 const double prevOpacity = mMarker->opacity();
4845 mMarker->setOpacity( mMarker->opacity() * context.opacity() );
4846 const bool useSelectedColor = shouldRenderUsingSelectionColor( context );
4847 render( context.renderContext(), QVector<Part>() << part, context.feature() ? *context.feature() : QgsFeature(), useSelectedColor );
4848 mMarker->setOpacity( prevOpacity );
4849 }
4850}
4851
4853{
4854 installMasks( context, true );
4855
4856 mRenderingFeature = true;
4857 mCurrentParts.clear();
4858}
4859
4861{
4862 mRenderingFeature = false;
4863
4864 const double prevOpacity = mMarker->opacity();
4865 mMarker->setOpacity( mMarker->opacity() * mFeatureSymbolOpacity );
4866
4867 render( context, mCurrentParts, feature, mUseSelectedColor );
4869 mUseSelectedColor = false;
4870 mMarker->setOpacity( prevOpacity );
4871
4872 removeMasks( context, true );
4873}
4874
4875void QgsCentroidFillSymbolLayer::render( QgsRenderContext &context, const QVector<QgsCentroidFillSymbolLayer::Part> &parts, const QgsFeature &feature, bool selected )
4876{
4879 bool clipPoints = mClipPoints;
4881
4882 // TODO add expressions support
4883
4884 QVector< QgsGeometry > geometryParts;
4885 geometryParts.reserve( parts.size() );
4886 QPainterPath globalPath;
4887
4888 int maxArea = 0;
4889 int maxAreaPartIdx = 0;
4890
4891 for ( int i = 0; i < parts.size(); i++ )
4892 {
4893 const Part part = parts[i];
4894 QgsGeometry geom = QgsGeometry::fromQPolygonF( part.exterior );
4895
4896 if ( !geom.isNull() && !part.rings.empty() )
4897 {
4898 QgsPolygon *poly = qgsgeometry_cast< QgsPolygon * >( geom.get() );
4899
4900 if ( !pointOnAllParts )
4901 {
4902 int area = poly->area();
4903
4904 if ( area > maxArea )
4905 {
4906 maxArea = area;
4907 maxAreaPartIdx = i;
4908 }
4909 }
4910 }
4911
4913 {
4914 globalPath.addPolygon( part.exterior );
4915 for ( const QPolygonF &ring : part.rings )
4916 {
4917 globalPath.addPolygon( ring );
4918 }
4919 }
4920 }
4921
4922 for ( int i = 0; i < parts.size(); i++ )
4923 {
4924 if ( !pointOnAllParts && i != maxAreaPartIdx )
4925 continue;
4926
4927 const Part part = parts[i];
4928
4929 if ( clipPoints )
4930 {
4931 QPainterPath path;
4932
4934 {
4935 path.addPolygon( part.exterior );
4936 for ( const QPolygonF &ring : part.rings )
4937 {
4938 path.addPolygon( ring );
4939 }
4940 }
4941 else
4942 {
4943 path = globalPath;
4944 }
4945
4946 context.painter()->save();
4947 context.painter()->setClipPath( path );
4948 }
4949
4950 QPointF centroid = pointOnSurface ? QgsSymbolLayerUtils::polygonPointOnSurface( part.exterior, &part.rings ) : QgsSymbolLayerUtils::polygonCentroid( part.exterior );
4951
4952 const bool prevIsSubsymbol = context.flags() & Qgis::RenderContextFlag::RenderingSubSymbol;
4954 mMarker->renderPoint( centroid, feature.isValid() ? &feature : nullptr, context, -1, selected );
4955 context.setFlag( Qgis::RenderContextFlag::RenderingSubSymbol, prevIsSubsymbol );
4956
4957 if ( clipPoints )
4958 {
4959 context.painter()->restore();
4960 }
4961 }
4962}
4963
4965{
4966 QVariantMap map;
4967 map[QStringLiteral( "point_on_surface" )] = QString::number( mPointOnSurface );
4968 map[QStringLiteral( "point_on_all_parts" )] = QString::number( mPointOnAllParts );
4969 map[QStringLiteral( "clip_points" )] = QString::number( mClipPoints );
4970 map[QStringLiteral( "clip_on_current_part_only" )] = QString::number( mClipOnCurrentPartOnly );
4971 return map;
4972}
4973
4975{
4976 std::unique_ptr< QgsCentroidFillSymbolLayer > x = std::make_unique< QgsCentroidFillSymbolLayer >();
4977 x->mAngle = mAngle;
4978 x->mColor = mColor;
4979 x->setSubSymbol( mMarker->clone() );
4980 x->setPointOnSurface( mPointOnSurface );
4981 x->setPointOnAllParts( mPointOnAllParts );
4982 x->setClipPoints( mClipPoints );
4983 x->setClipOnCurrentPartOnly( mClipOnCurrentPartOnly );
4984 copyDataDefinedProperties( x.get() );
4985 copyPaintEffect( x.get() );
4986 return x.release();
4987}
4988
4989void QgsCentroidFillSymbolLayer::toSld( QDomDocument &doc, QDomElement &element, const QVariantMap &props ) const
4990{
4991 // SLD 1.0 specs says: "if a line, polygon, or raster geometry is
4992 // used with PointSymbolizer, then the semantic is to use the centroid
4993 // of the geometry, or any similar representative point.
4994 mMarker->toSld( doc, element, props );
4995}
4996
4998{
5000 if ( !l )
5001 return nullptr;
5002
5003 QgsSymbolLayerList layers;
5004 layers.append( l );
5005 std::unique_ptr< QgsMarkerSymbol > marker( new QgsMarkerSymbol( layers ) );
5006
5007 std::unique_ptr< QgsCentroidFillSymbolLayer > sl = std::make_unique< QgsCentroidFillSymbolLayer >();
5008 sl->setSubSymbol( marker.release() );
5009 sl->setPointOnAllParts( false );
5010 return sl.release();
5011}
5012
5013
5018
5020{
5021 if ( !symbol || symbol->type() != Qgis::SymbolType::Marker )
5022 {
5023 delete symbol;
5024 return false;
5025 }
5026
5027 mMarker.reset( static_cast<QgsMarkerSymbol *>( symbol ) );
5028 mColor = mMarker->color();
5029 return true;
5030}
5031
5033{
5034 QSet<QString> attributes = QgsFillSymbolLayer::usedAttributes( context );
5035
5036 if ( mMarker )
5037 attributes.unite( mMarker->usedAttributes( context ) );
5038
5039 return attributes;
5040}
5041
5043{
5045 return true;
5046 if ( mMarker && mMarker->hasDataDefinedProperties() )
5047 return true;
5048 return false;
5049}
5050
5055
5057{
5058 if ( mMarker )
5059 {
5060 mMarker->setOutputUnit( unit );
5061 }
5062}
5063
5065{
5066 if ( mMarker )
5067 {
5068 return mMarker->outputUnit();
5069 }
5070 return Qgis::RenderUnit::Unknown; //mOutputUnit;
5071}
5072
5074{
5075 if ( mMarker )
5076 {
5077 return mMarker->usesMapUnits();
5078 }
5079 return false;
5080}
5081
5083{
5084 if ( mMarker )
5085 {
5086 mMarker->setMapUnitScale( scale );
5087 }
5088}
5089
5091{
5092 if ( mMarker )
5093 {
5094 return mMarker->mapUnitScale();
5095 }
5096 return QgsMapUnitScale();
5097}
5098
5099
5100
5101
5104 , mImageFilePath( imageFilePath )
5105{
5106 QgsImageFillSymbolLayer::setSubSymbol( nullptr ); //disable sub symbol
5108}
5109
5111
5112QgsSymbolLayer *QgsRasterFillSymbolLayer::create( const QVariantMap &properties )
5113{
5115 double alpha = 1.0;
5116 QPointF offset;
5117 double angle = 0.0;
5118 double width = 0.0;
5119
5120 QString imagePath;
5121 if ( properties.contains( QStringLiteral( "imageFile" ) ) )
5122 {
5123 imagePath = properties[QStringLiteral( "imageFile" )].toString();
5124 }
5125 if ( properties.contains( QStringLiteral( "coordinate_mode" ) ) )
5126 {
5127 mode = static_cast< Qgis::SymbolCoordinateReference >( properties[QStringLiteral( "coordinate_mode" )].toInt() );
5128 }
5129 if ( properties.contains( QStringLiteral( "alpha" ) ) )
5130 {
5131 alpha = properties[QStringLiteral( "alpha" )].toDouble();
5132 }
5133 if ( properties.contains( QStringLiteral( "offset" ) ) )
5134 {
5135 offset = QgsSymbolLayerUtils::decodePoint( properties[QStringLiteral( "offset" )].toString() );
5136 }
5137 if ( properties.contains( QStringLiteral( "angle" ) ) )
5138 {
5139 angle = properties[QStringLiteral( "angle" )].toDouble();
5140 }
5141 if ( properties.contains( QStringLiteral( "width" ) ) )
5142 {
5143 width = properties[QStringLiteral( "width" )].toDouble();
5144 }
5145 std::unique_ptr< QgsRasterFillSymbolLayer > symbolLayer = std::make_unique< QgsRasterFillSymbolLayer >( imagePath );
5146 symbolLayer->setCoordinateMode( mode );
5147 symbolLayer->setOpacity( alpha );
5148 symbolLayer->setOffset( offset );
5149 symbolLayer->setAngle( angle );
5150 symbolLayer->setWidth( width );
5151 if ( properties.contains( QStringLiteral( "offset_unit" ) ) )
5152 {
5153 symbolLayer->setOffsetUnit( QgsUnitTypes::decodeRenderUnit( properties[QStringLiteral( "offset_unit" )].toString() ) );
5154 }
5155 if ( properties.contains( QStringLiteral( "offset_map_unit_scale" ) ) )
5156 {
5157 symbolLayer->setOffsetMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( properties[QStringLiteral( "offset_map_unit_scale" )].toString() ) );
5158 }
5159 if ( properties.contains( QStringLiteral( "width_unit" ) ) )
5160 {
5161 symbolLayer->setSizeUnit( QgsUnitTypes::decodeRenderUnit( properties[QStringLiteral( "width_unit" )].toString() ) );
5162 }
5163 if ( properties.contains( QStringLiteral( "width_map_unit_scale" ) ) )
5164 {
5165 symbolLayer->setSizeMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( properties[QStringLiteral( "width_map_unit_scale" )].toString() ) );
5166 }
5167
5168 if ( properties.contains( QStringLiteral( "height" ) ) )
5169 {
5170 symbolLayer->setHeight( properties[QStringLiteral( "height" )].toDouble() );
5171 }
5172
5173 symbolLayer->restoreOldDataDefinedProperties( properties );
5174
5175 return symbolLayer.release();
5176}
5177
5179{
5180 QDomElement fillElem = element.firstChildElement( QStringLiteral( "Fill" ) );
5181 if ( fillElem.isNull() )
5182 return nullptr;
5183
5184 QDomElement graphicFillElem = fillElem.firstChildElement( QStringLiteral( "GraphicFill" ) );
5185 if ( graphicFillElem.isNull() )
5186 return nullptr;
5187
5188 QDomElement graphicElem = graphicFillElem.firstChildElement( QStringLiteral( "Graphic" ) );
5189 if ( graphicElem.isNull() )
5190 return nullptr;
5191
5192 QString path, mimeType;
5193 double size;
5194 QColor fillColor;
5195
5196 if ( !QgsSymbolLayerUtils::externalGraphicFromSld( graphicElem, path, mimeType, fillColor, size ) )
5197 return nullptr;
5198
5199 // Try to correct the path, this is a wild guess but we have not access to the SLD path here.
5200 if ( ! QFile::exists( path ) )
5201 {
5202 path = QgsProject::instance()->pathResolver().readPath( path ); // skip-keyword-check
5203 }
5204
5205 std::unique_ptr< QgsRasterFillSymbolLayer> sl = std::make_unique< QgsRasterFillSymbolLayer>( path );
5206
5207 return sl.release();
5208}
5209
5210void QgsRasterFillSymbolLayer::resolvePaths( QVariantMap &properties, const QgsPathResolver &pathResolver, bool saving )
5211{
5212 QVariantMap::iterator it = properties.find( QStringLiteral( "imageFile" ) );
5213 if ( it != properties.end() )
5214 {
5215 if ( saving )
5216 it.value() = pathResolver.writePath( it.value().toString() );
5217 else
5218 it.value() = pathResolver.readPath( it.value().toString() );
5219 }
5220}
5221
5223{
5224 Q_UNUSED( symbol )
5225 return true;
5226}
5227
5229{
5230 return QStringLiteral( "RasterFill" );
5231}
5232
5237
5238void QgsRasterFillSymbolLayer::renderPolygon( const QPolygonF &points, const QVector<QPolygonF> *rings, QgsSymbolRenderContext &context )
5239{
5240 QPainter *p = context.renderContext().painter();
5241 if ( !p )
5242 {
5243 return;
5244 }
5245
5246 QPointF offset = mOffset;
5248 {
5251 bool ok = false;
5252 const QPointF res = QgsSymbolLayerUtils::toPoint( val, &ok );
5253 if ( ok )
5254 offset = res;
5255 }
5256 if ( !offset.isNull() )
5257 {
5258 offset.setX( context.renderContext().convertToPainterUnits( offset.x(), mOffsetUnit, mOffsetMapUnitScale ) );
5259 offset.setY( context.renderContext().convertToPainterUnits( offset.y(), mOffsetUnit, mOffsetMapUnitScale ) );
5260 p->translate( offset );
5261 }
5262 if ( mCoordinateMode == Qgis::SymbolCoordinateReference::Feature )
5263 {
5264 QRectF boundingRect = points.boundingRect();
5265 mBrush.setTransform( mBrush.transform().translate( boundingRect.left() - mBrush.transform().dx(),
5266 boundingRect.top() - mBrush.transform().dy() ) );
5267 }
5268
5269 QgsImageFillSymbolLayer::renderPolygon( points, rings, context );
5270 if ( !offset.isNull() )
5271 {
5272 p->translate( -offset );
5273 }
5274}
5275
5277{
5278 applyPattern( mBrush, mImageFilePath, mWidth, mHeight, mOpacity * context.opacity(), context );
5279}
5280
5282{
5283 Q_UNUSED( context )
5284}
5285
5287{
5288 QVariantMap map;
5289 map[QStringLiteral( "imageFile" )] = mImageFilePath;
5290 map[QStringLiteral( "coordinate_mode" )] = QString::number( static_cast< int >( mCoordinateMode ) );
5291 map[QStringLiteral( "alpha" )] = QString::number( mOpacity );
5292 map[QStringLiteral( "offset" )] = QgsSymbolLayerUtils::encodePoint( mOffset );
5293 map[QStringLiteral( "offset_unit" )] = QgsUnitTypes::encodeUnit( mOffsetUnit );
5294 map[QStringLiteral( "offset_map_unit_scale" )] = QgsSymbolLayerUtils::encodeMapUnitScale( mOffsetMapUnitScale );
5295 map[QStringLiteral( "angle" )] = QString::number( mAngle );
5296
5297 map[QStringLiteral( "width" )] = QString::number( mWidth );
5298 map[QStringLiteral( "height" )] = QString::number( mHeight );
5299 map[QStringLiteral( "width_unit" )] = QgsUnitTypes::encodeUnit( mSizeUnit );
5300 map[QStringLiteral( "width_map_unit_scale" )] = QgsSymbolLayerUtils::encodeMapUnitScale( mSizeMapUnitScale );
5301
5302 return map;
5303}
5304
5306{
5307 std::unique_ptr< QgsRasterFillSymbolLayer > sl = std::make_unique< QgsRasterFillSymbolLayer >( mImageFilePath );
5308 sl->setCoordinateMode( mCoordinateMode );
5309 sl->setOpacity( mOpacity );
5310 sl->setOffset( mOffset );
5311 sl->setOffsetUnit( mOffsetUnit );
5312 sl->setOffsetMapUnitScale( mOffsetMapUnitScale );
5313 sl->setAngle( mAngle );
5314 sl->setWidth( mWidth );
5315 sl->setHeight( mHeight );
5316 sl->setSizeUnit( mSizeUnit );
5317 sl->setSizeMapUnitScale( mSizeMapUnitScale );
5318
5319 copyDataDefinedProperties( sl.get() );
5320 copyPaintEffect( sl.get() );
5321 return sl.release();
5322}
5323
5325{
5326 return context.convertToPainterUnits( std::max( std::fabs( mOffset.x() ), std::fabs( mOffset.y() ) ), mOffsetUnit, mOffsetMapUnitScale );
5327}
5328
5330{
5331 return mSizeUnit == Qgis::RenderUnit::MapUnits || mSizeUnit == Qgis::RenderUnit::MetersInMapUnits
5332 || mOffsetUnit == Qgis::RenderUnit::MapUnits || mOffsetUnit == Qgis::RenderUnit::MetersInMapUnits;
5333}
5334
5336{
5337 return QColor();
5338}
5339
5341{
5343 mOffsetUnit = unit;
5344 mSizeUnit = unit;
5345}
5346
5347void QgsRasterFillSymbolLayer::setImageFilePath( const QString &imagePath )
5348{
5349 mImageFilePath = imagePath;
5350}
5351
5353{
5354 mCoordinateMode = mode;
5355}
5356
5357void QgsRasterFillSymbolLayer::setOpacity( const double opacity )
5358{
5359 mOpacity = opacity;
5360}
5361
5363{
5364 if ( !dataDefinedProperties().hasActiveProperties() )
5365 return; // shortcut
5366
5367 const bool hasWidthExpression = mDataDefinedProperties.isActive( QgsSymbolLayer::Property::Width );
5368 const bool hasHeightExpression = mDataDefinedProperties.isActive( QgsSymbolLayer::Property::Height );
5369 const bool hasFileExpression = mDataDefinedProperties.isActive( QgsSymbolLayer::Property::File );
5370 const bool hasOpacityExpression = mDataDefinedProperties.isActive( QgsSymbolLayer::Property::Opacity );
5371 const bool hasAngleExpression = mDataDefinedProperties.isActive( QgsSymbolLayer::Property::Angle );
5372
5373 if ( !hasWidthExpression && !hasHeightExpression && !hasAngleExpression && !hasOpacityExpression && !hasFileExpression )
5374 {
5375 return; //no data defined settings
5376 }
5377
5378 bool ok;
5379 if ( hasAngleExpression )
5380 {
5383 if ( ok )
5384 mNextAngle = nextAngle;
5385 }
5386
5387 if ( !hasWidthExpression && !hasHeightExpression && !hasOpacityExpression && !hasFileExpression )
5388 {
5389 return; //nothing further to do
5390 }
5391
5392 double width = mWidth;
5393 if ( hasWidthExpression )
5394 {
5395 context.setOriginalValueVariable( mWidth );
5397 }
5398 double height = mHeight;
5399 if ( hasHeightExpression )
5400 {
5401 context.setOriginalValueVariable( mHeight );
5403 }
5404 double opacity = mOpacity;
5405 if ( hasOpacityExpression )
5406 {
5407 context.setOriginalValueVariable( mOpacity );
5409 }
5410 QString file = mImageFilePath;
5411 if ( hasFileExpression )
5412 {
5413 context.setOriginalValueVariable( mImageFilePath );
5415 }
5416 applyPattern( mBrush, file, width, height, opacity, context );
5417}
5418
5423
5424void QgsRasterFillSymbolLayer::applyPattern( QBrush &brush, const QString &imageFilePath, const double width, const double height, const double alpha, const QgsSymbolRenderContext &context )
5425{
5426 double imageWidth = 0;
5427 double imageHeight = 0;
5428
5429 // defer retrieval of original size till we actually NEED it
5430 QSize originalSize;
5431
5432 if ( width > 0 )
5433 {
5434 if ( mSizeUnit != Qgis::RenderUnit::Percentage )
5435 {
5436 imageWidth = context.renderContext().convertToPainterUnits( width, mSizeUnit, mSizeMapUnitScale );
5437 }
5438 else
5439 {
5440 // RenderPercentage Unit Type takes original image size
5442 if ( originalSize.isEmpty() )
5443 return;
5444
5445 imageWidth = ( width * originalSize.width() ) / 100.0;
5446
5447 // don't render symbols with size below one or above 10,000 pixels
5448 if ( static_cast< int >( imageWidth ) < 1 || 10000.0 < imageWidth )
5449 return;
5450 }
5451 }
5452 if ( height > 0 )
5453 {
5454 if ( mSizeUnit != Qgis::RenderUnit::Percentage )
5455 {
5456 imageHeight = context.renderContext().convertToPainterUnits( height, mSizeUnit, mSizeMapUnitScale );
5457 }
5458 else
5459 {
5460 // RenderPercentage Unit Type takes original image size
5461 if ( !originalSize.isValid() )
5463
5464 if ( originalSize.isEmpty() )
5465 return;
5466
5467 imageHeight = ( height * originalSize.height() ) / 100.0;
5468
5469 // don't render symbols with size below one or above 10,000 pixels
5470 if ( static_cast< int >( imageHeight ) < 1 || 10000.0 < imageHeight )
5471 return;
5472 }
5473 }
5474
5475 if ( width == 0 && imageHeight > 0 )
5476 {
5477 if ( !originalSize.isValid() )
5479
5480 imageWidth = imageHeight * originalSize.width() / originalSize.height();
5481 }
5482 else if ( height == 0 && imageWidth > 0 )
5483 {
5484 if ( !originalSize.isValid() )
5486
5487 imageHeight = imageWidth * originalSize.height() / originalSize.width();
5488 }
5489 if ( imageWidth == 0 || imageHeight == 0 )
5490 {
5491 if ( !originalSize.isValid() )
5493
5494 imageWidth = originalSize.width();
5495 imageHeight = originalSize.height();
5496 }
5497
5498 bool cached;
5499 QImage img = QgsApplication::imageCache()->pathAsImage( imageFilePath, QSize( std::round< int >( imageWidth ), std::round< int >( imageHeight ) ), false, alpha, cached, ( context.renderContext().flags() & Qgis::RenderContextFlag::RenderBlocking ) );
5500 if ( img.isNull() )
5501 return;
5502
5503 brush.setTextureImage( img );
5504}
5505
5506
5507//
5508// QgsRandomMarkerFillSymbolLayer
5509//
5510
5511QgsRandomMarkerFillSymbolLayer::QgsRandomMarkerFillSymbolLayer( int pointCount, Qgis::PointCountMethod method, double densityArea, unsigned long seed )
5512 : mCountMethod( method )
5513 , mPointCount( pointCount )
5514 , mDensityArea( densityArea )
5515 , mSeed( seed )
5516{
5518}
5519
5521
5523{
5524 const Qgis::PointCountMethod countMethod = static_cast< Qgis::PointCountMethod >( properties.value( QStringLiteral( "count_method" ), QStringLiteral( "0" ) ).toInt() );
5525 const int pointCount = properties.value( QStringLiteral( "point_count" ), QStringLiteral( "10" ) ).toInt();
5526 const double densityArea = properties.value( QStringLiteral( "density_area" ), QStringLiteral( "250.0" ) ).toDouble();
5527
5528 unsigned long seed = 0;
5529 if ( properties.contains( QStringLiteral( "seed" ) ) )
5530 seed = properties.value( QStringLiteral( "seed" ) ).toUInt();
5531 else
5532 {
5533 // if we a creating a new random marker fill from scratch, we default to a random seed
5534 // because seed based fills are just nicer for users vs seeing points jump around with every map refresh
5535 std::random_device rd;
5536 std::mt19937 mt( seed == 0 ? rd() : seed );
5537 std::uniform_int_distribution<> uniformDist( 1, 999999999 );
5538 seed = uniformDist( mt );
5539 }
5540
5541 std::unique_ptr< QgsRandomMarkerFillSymbolLayer > sl = std::make_unique< QgsRandomMarkerFillSymbolLayer >( pointCount, countMethod, densityArea, seed );
5542
5543 if ( properties.contains( QStringLiteral( "density_area_unit" ) ) )
5544 sl->setDensityAreaUnit( QgsUnitTypes::decodeRenderUnit( properties[QStringLiteral( "density_area_unit" )].toString() ) );
5545 if ( properties.contains( QStringLiteral( "density_area_unit_scale" ) ) )
5546 sl->setDensityAreaUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( properties[QStringLiteral( "density_area_unit_scale" )].toString() ) );
5547
5548 if ( properties.contains( QStringLiteral( "clip_points" ) ) )
5549 {
5550 sl->setClipPoints( properties[QStringLiteral( "clip_points" )].toInt() );
5551 }
5552
5553 return sl.release();
5554}
5555
5557{
5558 return QStringLiteral( "RandomMarkerFill" );
5559}
5560
5562{
5563 mMarker->setColor( color );
5564 mColor = color;
5565}
5566
5568{
5569 return mMarker ? mMarker->color() : mColor;
5570}
5571
5573{
5574 mMarker->setRenderHints( mMarker->renderHints() | Qgis::SymbolRenderHint::IsSymbolLayerSubSymbol );
5575 mMarker->startRender( context.renderContext(), context.fields() );
5576}
5577
5579{
5580 mMarker->stopRender( context.renderContext() );
5581}
5582
5583void QgsRandomMarkerFillSymbolLayer::renderPolygon( const QPolygonF &points, const QVector<QPolygonF> *rings, QgsSymbolRenderContext &context )
5584{
5585 Part part;
5586 part.exterior = points;
5587 if ( rings )
5588 part.rings = *rings;
5589
5590 if ( mRenderingFeature )
5591 {
5592 // in the middle of rendering a possibly multi-part feature, so we collect all the parts and defer the actual rendering
5593 // until after we've received the final part
5594 mFeatureSymbolOpacity = context.opacity();
5595 mCurrentParts << part;
5596 }
5597 else
5598 {
5599 // not rendering a feature, so we can just render the polygon immediately
5600 const double prevOpacity = mMarker->opacity();
5601 mMarker->setOpacity( mMarker->opacity() * context.opacity() );
5602 const bool useSelectedColor = shouldRenderUsingSelectionColor( context );
5603 render( context.renderContext(), QVector< Part>() << part, context.feature() ? *context.feature() : QgsFeature(), useSelectedColor );
5604 mMarker->setOpacity( prevOpacity );
5605 }
5606}
5607
5608void QgsRandomMarkerFillSymbolLayer::render( QgsRenderContext &context, const QVector<QgsRandomMarkerFillSymbolLayer::Part> &parts, const QgsFeature &feature, bool selected )
5609{
5610 bool clipPoints = mClipPoints;
5612 {
5615 }
5616
5617 QVector< QgsGeometry > geometryParts;
5618 geometryParts.reserve( parts.size() );
5619 QPainterPath path;
5620
5621 for ( const Part &part : parts )
5622 {
5623 QgsGeometry geom = QgsGeometry::fromQPolygonF( part.exterior );
5624 if ( !geom.isNull() && !part.rings.empty() )
5625 {
5626 QgsPolygon *poly = qgsgeometry_cast< QgsPolygon * >( geom.get() );
5627 for ( const QPolygonF &ring : part.rings )
5628 {
5630 }
5631 }
5632 if ( !geom.isGeosValid() )
5633 {
5634 geom = geom.buffer( 0, 0 );
5635 }
5636 geometryParts << geom;
5637
5638 if ( clipPoints )
5639 {
5640 path.addPolygon( part.exterior );
5641 for ( const QPolygonF &ring : part.rings )
5642 {
5643 path.addPolygon( ring );
5644 }
5645 }
5646 }
5647
5648 const QgsGeometry geom = geometryParts.count() != 1 ? QgsGeometry::unaryUnion( geometryParts ) : geometryParts.at( 0 );
5649
5650 if ( clipPoints )
5651 {
5652 context.painter()->save();
5653 context.painter()->setClipPath( path );
5654 }
5655
5656
5657 int count = mPointCount;
5659 {
5662 }
5663
5664 switch ( mCountMethod )
5665 {
5667 {
5668 double densityArea = mDensityArea;
5670 {
5673 }
5674 densityArea = context.convertToPainterUnits( std::sqrt( densityArea ), mDensityAreaUnit, mDensityAreaUnitScale );
5675 densityArea = std::pow( densityArea, 2 );
5676 count = std::max( 0.0, std::ceil( count * ( geom.area() / densityArea ) ) );
5677 break;
5678 }
5680 break;
5681 }
5682
5683 unsigned long seed = mSeed;
5685 {
5686 context.expressionContext().setOriginalValueVariable( static_cast< unsigned long long >( seed ) );
5688 }
5689
5690 QVector< QgsPointXY > randomPoints = geom.randomPointsInPolygon( count, seed );
5691#if 0
5692 // in some cases rendering from top to bottom is nice (e.g. randomised tree markers), but in other cases it's not wanted..
5693 // TODO consider exposing this as an option
5694 std::sort( randomPoints.begin(), randomPoints.end(), []( const QgsPointXY & a, const QgsPointXY & b )->bool
5695 {
5696 return a.y() < b.y();
5697 } );
5698#endif
5700 QgsExpressionContextScopePopper scopePopper( context.expressionContext(), scope );
5701 int pointNum = 0;
5702 const bool needsExpressionContext = mMarker->hasDataDefinedProperties();
5703
5704 const bool prevIsSubsymbol = context.flags() & Qgis::RenderContextFlag::RenderingSubSymbol;
5706
5707 for ( const QgsPointXY &p : std::as_const( randomPoints ) )
5708 {
5709 if ( needsExpressionContext )
5711 mMarker->renderPoint( QPointF( p.x(), p.y() ), feature.isValid() ? &feature : nullptr, context, -1, selected );
5712 }
5713
5714 context.setFlag( Qgis::RenderContextFlag::RenderingSubSymbol, prevIsSubsymbol );
5715
5716 if ( clipPoints )
5717 {
5718 context.painter()->restore();
5719 }
5720}
5721
5723{
5724 QVariantMap map;
5725 map.insert( QStringLiteral( "count_method" ), QString::number( static_cast< int >( mCountMethod ) ) );
5726 map.insert( QStringLiteral( "point_count" ), QString::number( mPointCount ) );
5727 map.insert( QStringLiteral( "density_area" ), QString::number( mDensityArea ) );
5728 map.insert( QStringLiteral( "density_area_unit" ), QgsUnitTypes::encodeUnit( mDensityAreaUnit ) );
5729 map.insert( QStringLiteral( "density_area_unit_scale" ), QgsSymbolLayerUtils::encodeMapUnitScale( mDensityAreaUnitScale ) );
5730 map.insert( QStringLiteral( "seed" ), QString::number( mSeed ) );
5731 map.insert( QStringLiteral( "clip_points" ), QString::number( mClipPoints ) );
5732 return map;
5733}
5734
5736{
5737 std::unique_ptr< QgsRandomMarkerFillSymbolLayer > res = std::make_unique< QgsRandomMarkerFillSymbolLayer >( mPointCount, mCountMethod, mDensityArea, mSeed );
5738 res->mAngle = mAngle;
5739 res->mColor = mColor;
5740 res->setDensityAreaUnit( mDensityAreaUnit );
5741 res->setDensityAreaUnitScale( mDensityAreaUnitScale );
5742 res->mClipPoints = mClipPoints;
5743 res->setSubSymbol( mMarker->clone() );
5744 copyDataDefinedProperties( res.get() );
5745 copyPaintEffect( res.get() );
5746 return res.release();
5747}
5748
5753
5755{
5756 return mMarker.get();
5757}
5758
5760{
5761 if ( !symbol || symbol->type() != Qgis::SymbolType::Marker )
5762 {
5763 delete symbol;
5764 return false;
5765 }
5766
5767 mMarker.reset( static_cast<QgsMarkerSymbol *>( symbol ) );
5768 mColor = mMarker->color();
5769 return true;
5770}
5771
5773{
5774 QSet<QString> attributes = QgsFillSymbolLayer::usedAttributes( context );
5775
5776 if ( mMarker )
5777 attributes.unite( mMarker->usedAttributes( context ) );
5778
5779 return attributes;
5780}
5781
5783{
5785 return true;
5786 if ( mMarker && mMarker->hasDataDefinedProperties() )
5787 return true;
5788 return false;
5789}
5790
5792{
5793 return mPointCount;
5794}
5795
5797{
5798 mPointCount = pointCount;
5799}
5800
5802{
5803 return mSeed;
5804}
5805
5807{
5808 mSeed = seed;
5809}
5810
5812{
5813 return mClipPoints;
5814}
5815
5817{
5818 mClipPoints = clipPoints;
5819}
5820
5822{
5823 return mCountMethod;
5824}
5825
5827{
5828 mCountMethod = method;
5829}
5830
5832{
5833 return mDensityArea;
5834}
5835
5837{
5838 mDensityArea = area;
5839}
5840
5842{
5843 installMasks( context, true );
5844
5845 mRenderingFeature = true;
5846 mCurrentParts.clear();
5847}
5848
5850{
5851 mRenderingFeature = false;
5852
5853 const double prevOpacity = mMarker->opacity();
5854 mMarker->setOpacity( mMarker->opacity() * mFeatureSymbolOpacity );
5855
5856 render( context, mCurrentParts, feature, false );
5857
5858 mFeatureSymbolOpacity = 1;
5859 mMarker->setOpacity( prevOpacity );
5860
5861 removeMasks( context, true );
5862}
5863
5864
5866{
5867 mDensityAreaUnit = unit;
5868 if ( mMarker )
5869 {
5870 mMarker->setOutputUnit( unit );
5871 }
5872}
5873
5875{
5876 if ( mMarker )
5877 {
5878 return mMarker->outputUnit();
5879 }
5880 return Qgis::RenderUnit::Unknown; //mOutputUnit;
5881}
5882
5884{
5885 if ( mMarker )
5886 {
5887 return mMarker->usesMapUnits();
5888 }
5889 return false;
5890}
5891
5893{
5894 if ( mMarker )
5895 {
5896 mMarker->setMapUnitScale( scale );
5897 }
5898}
5899
5901{
5902 if ( mMarker )
5903 {
5904 return mMarker->mapUnitScale();
5905 }
5906 return QgsMapUnitScale();
5907}
MarkerClipMode
Marker clipping modes.
Definition qgis.h:3026
@ CompletelyWithin
Render complete markers wherever the completely fall within the polygon shape.
@ NoClipping
No clipping, render complete markers.
@ Shape
Clip to polygon shape.
@ CentroidWithin
Render complete markers wherever their centroid falls within the polygon shape.
@ IsSymbolLayerSubSymbol
Symbol is being rendered as a sub-symbol of a QgsSymbolLayer.
LineClipMode
Line clipping modes.
Definition qgis.h:3040
@ NoClipping
Lines are not clipped, will extend to shape's bounding box.
@ ClipPainterOnly
Applying clipping on the painter only (i.e. line endpoints will coincide with polygon bounding box,...
@ ClipToIntersection
Clip lines to intersection with polygon shape (slower) (i.e. line endpoints will coincide with polygo...
GradientColorSource
Gradient color sources.
Definition qgis.h:2955
@ ColorRamp
Gradient color ramp.
@ SimpleTwoColor
Simple two color gradient.
@ CanCalculateMaskGeometryPerFeature
If present, indicates that mask geometry can safely be calculated per feature for the symbol layer....
GradientSpread
Gradient spread options, which control how gradients are rendered outside of their start and end poin...
Definition qgis.h:2999
@ Repeat
Repeat gradient.
@ Reflect
Reflect gradient.
@ Pad
Pad out gradient using colors at endpoint of gradient.
@ Png
Export complex styles to separate PNG files for better compatibility with OGC servers.
PointCountMethod
Methods which define the number of points randomly filling a polygon.
Definition qgis.h:3014
@ Absolute
The point count is used as an absolute count of markers.
@ DensityBased
The point count is part of a marker density count.
QFlags< SymbolLayerFlag > SymbolLayerFlags
Symbol layer flags.
Definition qgis.h:821
RenderUnit
Rendering size units.
Definition qgis.h:4847
@ Percentage
Percentage of another measurement (e.g., canvas size, feature size)
@ Unknown
Mixed or unknown units.
@ MapUnits
Map units.
@ MetersInMapUnits
Meters value as Map units.
@ RenderingSubSymbol
Set whenever a sub-symbol of a parent symbol is currently being rendered. Can be used during symbol a...
@ RenderSymbolPreview
The render is for a symbol preview only and map based properties may not be available,...
@ RenderMapTile
Draw map such that there are no problems between adjacent tiles.
@ HighQualityImageTransforms
Enable high quality image transformations, which results in better appearance of scaled or rotated ra...
@ RenderBlocking
Render and load remote sources in the same thread to ensure rendering remote sources (svg and images)...
GradientType
Gradient types.
Definition qgis.h:2969
@ Linear
Linear gradient.
@ Conical
Conical (polar) gradient.
@ Radial
Radial (circular) gradient.
QFlags< SymbolRenderHint > SymbolRenderHints
Symbol render hints.
Definition qgis.h:741
@ Marker
Marker symbol.
@ Line
Line symbol.
SymbolCoordinateReference
Symbol coordinate reference modes.
Definition qgis.h:2984
@ Feature
Relative to feature/shape being rendered.
@ Viewport
Relative to the whole viewport/output device.
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.
int valueAsInt(int key, const QgsExpressionContext &context, int defaultValue=0, bool *ok=nullptr) const
Calculates the current value of the property with the specified key and interprets it as an integer.
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.
double valueAsDouble(int key, const QgsExpressionContext &context, double defaultValue=0.0, bool *ok=nullptr) const
Calculates the current value of the property with the specified key and interprets it as a double.
QString valueAsString(int key, const QgsExpressionContext &context, const QString &defaultString=QString(), bool *ok=nullptr) const
Calculates the current value of the property with the specified key and interprets it as a string.
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...
A fill symbol layer which renders a marker symbol at the centroid of a polygon geometry.
static QgsSymbolLayer * createFromSld(QDomElement &element)
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...
QgsMapUnitScale mapUnitScale() const override
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.
bool setSubSymbol(QgsSymbol *symbol) FINAL
Sets layer's subsymbol. takes ownership of the passed symbol.
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.
void toSld(QDomDocument &doc, QDomElement &element, const QVariantMap &props) const override
Saves the symbol layer as SLD.
static QgsSymbolLayer * create(const QVariantMap &properties=QVariantMap())
Creates a new QgsCentroidFillSymbolLayer using the specified properties map containing symbol propert...
~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 QVariantMap properties() const =0
Returns a string map containing all the color ramp's properties.
virtual QgsColorRamp * clone() const =0
Creates a clone of the color ramp.
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 QgsColorRamp * create(const QVariantMap &properties=QVariantMap())
Creates the symbol layer.
static QString typeString()
Returns the string identifier for QgsCptCityColorRamp.
double area() const override
Returns the planar, 2-dimensional area of the geometry.
Exports QGIS layers to the DXF format.
static double mapUnitScaleFactor(double scale, Qgis::RenderUnit symbolUnits, Qgis::DistanceUnit mapUnits, double mapUnitsPerPixel=1.0)
Returns scale factor for conversion to map units.
Qgis::DistanceUnit mapUnits() const
Retrieve map units.
double symbologyScale() const
Returns the reference scale for output.
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:58
bool isValid() const
Returns the validity of this feature.
bool isCanceled() const
Tells whether the operation has been canceled already.
Definition qgsfeedback.h:53
static QString uniquePath(const QString &path)
Creates a unique file path name from a desired path by appending _<n> (where <n> is an integer number...
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.
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 contains(const QgsPointXY *p) const
Returns true if the geometry contains the point p.
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.
QgsGeometry buffer(double distance, int segments) const
Returns a buffer region around this geometry having the given width and with a specified number of se...
static QgsGeometry unaryUnion(const QVector< QgsGeometry > &geometries, const QgsGeometryParameters &parameters=QgsGeometryParameters())
Compute the unary union on a list of geometries.
static 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...
Gradient color ramp, which smoothly interpolates between two colors and also supports optional extra ...
static 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.
A fill symbol layer which draws a smooth color gradient over a polygon.
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.
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.
static QgsSymbolLayer * create(const QVariantMap &properties=QVariantMap())
Creates a new QgsGradientFillSymbolLayer using the specified properties map containing symbol propert...
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].
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.
Base class for polygon renderers generating texture images.
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
double dxfWidth(const QgsDxfExport &e, QgsSymbolRenderContext &context) const override
Gets line width.
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.
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.
A symbol fill consisting of repeated parallel lines.
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.
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.
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
double estimateMaxBleed(const QgsRenderContext &context) const override
Returns the estimated maximum distance which the layer style will bleed outside the drawn shape when ...
static QgsSymbolLayer * createFromSld(QDomElement &element)
Creates a new QgsLinePatternFillSymbolLayer from a SLD element.
static QgsSymbolLayer * create(const QVariantMap &properties=QVariantMap())
Creates a new QgsLinePatternFillSymbolLayer from a properties map.
Line string geometry type, with support for z-dimension and m-values.
QPolygonF asQPolygonF() const override
Returns a QPolygonF representing the points.
static QgsLineString * fromQPolygonF(const QPolygonF &polygon)
Returns a new linestring from a QPolygonF polygon input.
A line symbol type, for rendering LineString and MultiLineString geometries.
Perform transforms between map coordinates and device coordinates.
double mapUnitsPerPixel() const
Returns the current map units per pixel.
Struct for storing maximum and minimum scales for measurements in map units.
Line symbol layer type which draws repeating marker symbols along a line feature.
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)
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.
A fill symbol layer which fills polygon shapes with repeating marker symbols.
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.
static QgsSymbolLayer * create(const QVariantMap &properties=QVariantMap())
Creates a new QgsPointPatternFillSymbolLayer using the specified properties map containing symbol pro...
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.
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.
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.
void setClipMode(Qgis::MarkerClipMode mode)
Sets the marker clipping mode, which defines how markers are clipped at the edges of shapes.
static QgsSymbolLayer * createFromSld(QDomElement &element)
A class to represent a 2D point.
Definition qgspointxy.h:60
Point geometry type, with support for z-dimension and m-values.
Definition qgspoint.h:49
double x
Definition qgspoint.h:52
double y
Definition qgspoint.h:53
Polygon geometry type.
Definition qgspolygon.h:33
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...
QVariant value(int key, const QgsExpressionContext &context, const QVariant &defaultValue=QVariant()) const final
Returns the calculated value of the property with the specified key from within the collection.
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.
A fill symbol layer which places markers at random locations within polygons.
~QgsRandomMarkerFillSymbolLayer() override
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...
static QgsSymbolLayer * create(const QVariantMap &properties=QVariantMap())
Creates a new QgsRandomMarkerFillSymbolLayer using the specified properties map containing symbol pro...
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.
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.
void setColor(const QColor &color) override
Sets the "representative" color for the symbol layer.
bool setSubSymbol(QgsSymbol *symbol) FINAL
Sets layer's subsymbol. takes ownership of the passed symbol.
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
A class for filling symbols with a repeated raster image.
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,...
static QgsSymbolLayer * createFromSld(QDomElement &element)
Creates a new QgsRasterFillSymbolLayer from a SLD element.
static QgsSymbolLayer * create(const QVariantMap &properties=QVariantMap())
Creates a new QgsRasterFillSymbolLayer from a properties map.
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 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.
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.
void setForceVectorOutput(bool force)
Sets whether rendering operations should use vector operations instead of any faster raster shortcuts...
double scaleFactor() const
Returns the scaling factor for the render to convert painter units to physical sizes.
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 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...
A class for filling symbols with a repeated SVG file.
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.
static QgsSymbolLayer * createFromSld(QDomElement &element)
Creates a new QgsSVGFillSymbolLayer from a SLD element.
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.
static QgsSymbolLayer * create(const QVariantMap &properties=QVariantMap())
Creates a new QgsSVGFillSymbolLayer from a properties map.
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.
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
void toSld(QDomDocument &doc, QDomElement &element, const QVariantMap &props) const override
Saves the symbol layer as SLD.
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.
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 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.
Renders polygons using a single fill and stroke color.
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)
double dxfWidth(const QgsDxfExport &e, QgsSymbolRenderContext &context) const override
Gets line width.
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
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
QImage toTiledPatternImage() const override
Renders the symbol layer as an image that can be used as a seamless pattern fill for polygons,...
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.
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...
static QgsSymbolLayer * create(const QVariantMap &properties=QVariantMap())
Creates a new QgsSimpleFillSymbolLayer using the specified properties map containing symbol propertie...
static QgsSymbolLayer * createFromSld(QDomElement &element)
The QgsSldExportContext class holds SLD export options and other information related to SLD export of...
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.
Contains utility functions for working with symbols and symbol layers.
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 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 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 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 void lineToSld(QDomDocument &doc, QDomElement &element, Qt::PenStyle penStyle, const QColor &color, double width=-1, const Qt::PenJoinStyle *penJoinStyle=nullptr, const Qt::PenCapStyle *penCapStyle=nullptr, const QVector< qreal > *customDashPattern=nullptr, double dashOffset=0.0)
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)
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)
static bool fillFromSld(QDomElement &element, Qt::BrushStyle &brushStyle, QColor &color)
static void fillToSld(QDomDocument &doc, QDomElement &element, Qt::BrushStyle brushStyle, const QColor &color=QColor())
static Qgis::RenderUnit decodeSldUom(const QString &str, double *scaleFactor=nullptr)
Decodes a SLD unit of measure string to a render unit.
static void createGeometryElement(QDomDocument &doc, QDomElement &element, const QString &geomFunc)
static double estimateMaxSymbolBleed(QgsSymbol *symbol, const QgsRenderContext &context)
Returns the maximum estimated bleed for the symbol.
static void wellKnownMarkerToSld(QDomDocument &doc, QDomElement &element, const QString &name, const QColor &color, const QColor &strokeColor, Qt::PenStyle strokeStyle, double strokeWidth=-1, double size=-1)
static Qt::PenStyle decodePenStyle(const QString &str)
static void createRotationElement(QDomDocument &doc, QDomElement &element, const QString &rotationFunc)
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 QgsSymbolLayer * createMarkerLayerFromSld(QDomElement &element)
static QString encodePenJoinStyle(Qt::PenJoinStyle style)
static QgsStringMap getVendorOptionList(QDomElement &element)
static QPointF decodePoint(const QString &string)
Decodes a QSizeF from a string.
static QgsSymbolLayer * createLineLayerFromSld(QDomElement &element)
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.
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
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.
void copyDataDefinedProperties(QgsSymbolLayer *destLayer) const
Copies all data defined properties of this layer to another symbol 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.
@ PointCount
Point count.
@ GradientSpread
Gradient spread mode.
@ ShapeburstMaxDistance
Shapeburst fill from edge distance.
@ StrokeStyle
Stroke style (eg solid, dashed)
@ DistanceY
Vertical distance between points.
@ DensityArea
Density area.
@ 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.
@ StrokeColor
Stroke color.
@ 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.
@ StrokeWidth
Stroke width.
@ GradientReference2IsCentroid
Gradient reference point 2 is centroid.
@ LineDistance
Distance between lines, or length of lines for hash line symbols.
@ Offset
Symbol offset.
@ RandomOffsetX
Random offset X.
@ Height
Symbol height.
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 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.
void copyPaintEffect(QgsSymbolLayer *destLayer) const
Copies paint effect of this layer to another 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.
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.
Abstract base class for all rendered symbols.
Definition qgssymbol.h:231
QColor color() const
Returns the symbol's color.
Qgis::SymbolType type() const
Returns the symbol's type.
Definition qgssymbol.h:293
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:5875
bool qgsDoubleNear(double a, double b, double epsilon=4 *std::numeric_limits< double >::epsilon())
Compare two doubles (but allow some difference)
Definition qgis.h:5958
QMap< QString, QString > QgsStringMap
Definition qgis.h:6496
#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
QList< QgsSymbolLayer * > QgsSymbolLayerList
Definition qgssymbol.h:30
Single variable definition for use within a QgsExpressionContextScope.