QGIS API Documentation 3.99.0-Master (d270888f95f)
Loading...
Searching...
No Matches
qgsrasterlabeling.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgsrasterlabeling.cpp
3 ---------------
4 begin : December 2024
5 copyright : (C) 2024 by Nyall Dawson
6 email : nyall dot dawson at gmail dot com
7 ***************************************************************************/
8/***************************************************************************
9 * *
10 * This program is free software; you can redistribute it and/or modify *
11 * it under the terms of the GNU General Public License as published by *
12 * the Free Software Foundation; either version 2 of the License, or *
13 * (at your option) any later version. *
14 * *
15 ***************************************************************************/
16
17#include "qgsrasterlabeling.h"
18
19#include "feature.h"
20#include "labelposition.h"
21#include "qgsapplication.h"
23#include "qgsmessagelog.h"
24#include "qgsnumericformat.h"
26#include "qgsrasterlayer.h"
28#include "qgsrasterpipe.h"
29#include "qgsscaleutils.h"
30#include "qgsstyle.h"
32#include "qgstextlabelfeature.h"
33#include "qgstextrenderer.h"
34
35#include <QString>
36
37using namespace Qt::StringLiterals;
38
46
51
52void QgsRasterLayerLabelProvider::addLabel( const QgsPoint &mapPoint, const QString &text, QgsRenderContext &context )
53{
54 QgsPoint geom = mapPoint;
55 const QgsTextDocument doc = QgsTextDocument::fromTextAndFormat( text.split( "\n" ), mFormat );
56 QgsTextDocumentMetrics documentMetrics = QgsTextDocumentMetrics::calculateMetrics( doc, mFormat, context );
58
59
60 // Rotate the geometry if needed, before clipping
61 const QgsMapToPixel &m2p = context.mapToPixel();
62 if ( !qgsDoubleNear( m2p.mapRotation(), 0 ) )
63 {
64 QgsPointXY center = context.mapExtent().center();
65
66 QTransform t = QTransform::fromTranslate( center.x(), center.y() );
67 t.rotate( - m2p.mapRotation() );
68 t.translate( -center.x(), -center.y() );
69 geom.transform( t );
70 }
71
72 const double uPP = m2p.mapUnitsPerPixel();
73 auto feature = std::make_unique< QgsTextLabelFeature >( mLabels.size(),
74 QgsGeos::asGeos( &geom ),
75 QSizeF( size.width() * uPP,
76 size.height() * uPP ) );
77
78 feature->setDocument( doc, documentMetrics );
79 feature->setFixedAngle( 0 );
80 feature->setHasFixedAngle( true );
81 feature->setQuadOffset( QPointF( 0, 0 ) );
82 feature->setZIndex( mZIndex );
83
84 feature->setOverlapHandling( mPlacementSettings.overlapHandling() );
85
86 mLabels.append( feature.release() );
87}
88
90{
91 mFormat = format;
92}
93
94void QgsRasterLayerLabelProvider::setNumericFormat( std::unique_ptr<QgsNumericFormat> format )
95{
96 mNumericFormat = std::move( format );
97}
98
100{
101 return mNumericFormat.get();
102}
103
105{
106 mResampleMethod = method;
107}
108
110{
111 mResampleOver = pixels;
112}
113
115{
116 return mLabels;
117}
118
120{
121 // as per vector label rendering...
122 QgsMapToPixel xform = context.mapToPixel();
123 xform.setMapRotation( 0, 0, 0 );
124 const QPointF outPt = xform.transform( label->getX(), label->getY() ).toQPointF();
125
126 QgsTextLabelFeature *lf = qgis::down_cast<QgsTextLabelFeature *>( label->getFeaturePart()->feature() );
128 mFormat, lf->document(), lf->documentMetrics(), context, Qgis::TextHorizontalAlignment::Left,
130}
131
133{
134 if ( mFormat.dataDefinedProperties().hasActiveProperties() )
135 mFormat.updateDataDefinedProperties( context );
137}
138
140// RAII properties restorer for QgsRasterDataProvider
141struct RasterProviderSettingsRestorer
142{
143 QgsRasterDataProvider *mProvider;
144 const bool mProviderResampling;
145 const Qgis::RasterResamplingMethod mZoomedOutMethod;
146 const double mMaxOversampling;
147
148 RasterProviderSettingsRestorer( QgsRasterDataProvider *provider )
149 : mProvider( provider )
150 , mProviderResampling( provider->isProviderResamplingEnabled() )
151 , mZoomedOutMethod( provider->zoomedOutResamplingMethod() )
152 , mMaxOversampling( provider->maxOversampling() ) {}
153
154 ~RasterProviderSettingsRestorer()
155 {
156 mProvider->enableProviderResampling( mProviderResampling );
157 mProvider->setZoomedOutResamplingMethod( mZoomedOutMethod );
158 mProvider->setMaxOversampling( mMaxOversampling );
159 }
160};
162
163void QgsRasterLayerLabelProvider::generateLabels( QgsRenderContext &context, QgsRasterPipe *pipe, QgsRasterViewPort *rasterViewPort, QgsRasterLayerRendererFeedback *feedback )
164{
165 if ( !pipe )
166 return;
167
168 QgsRasterDataProvider *provider = pipe->provider();
169 if ( !provider )
170 return;
171
172 if ( provider->xSize() == 0 || provider->ySize() == 0 )
173 return;
174
175 if ( !rasterViewPort )
176 return;
177
178 // iterate through blocks, directly over the provider.
179 QgsRasterIterator iterator( provider );
180
181 const QSize maxTileSize {provider->maximumTileSize()};
182 iterator.setMaximumTileWidth( maxTileSize.width() );
183 iterator.setMaximumTileHeight( maxTileSize.height() );
184 iterator.setSnapToPixelFactor( mResampleOver );
185
186 // we need to calculate the visible portion of the layer, in the original (layer) CRS:
187 QgsCoordinateTransform layerToMapTransform = context.coordinateTransform();
188 layerToMapTransform.setBallparkTransformsAreAppropriate( true );
189 QgsRectangle layerVisibleExtent;
190 try
191 {
192 layerVisibleExtent = layerToMapTransform.transformBoundingBox( rasterViewPort->mDrawnExtent, Qgis::TransformDirection::Reverse );
193 }
194 catch ( QgsCsException &cs )
195 {
196 QgsMessageLog::logMessage( QObject::tr( "Could not reproject view extent: %1" ).arg( cs.what() ), QObject::tr( "Raster" ) );
197 return;
198 }
199
200 const int maxNumLabels = mThinningSettings.limitNumberOfLabelsEnabled() ? mThinningSettings.maximumNumberLabels() : 0;
201
202 // calculate the portion of the raster which is actually visible in the map
203 int subRegionWidth = 0;
204 int subRegionHeight = 0;
205 int subRegionLeft = 0;
206 int subRegionTop = 0;
208 provider->extent(),
209 provider->xSize(),
210 provider->ySize(),
211 layerVisibleExtent,
212 subRegionWidth,
213 subRegionHeight,
214 subRegionLeft,
215 subRegionTop );
216
217 const double rasterUnitsPerPixelX = provider->extent().width() / provider->xSize() * mResampleOver;
218 const double rasterUnitsPerPixelY = provider->extent().height() / provider->ySize() * mResampleOver;
219
220 const double minPixelSizePainterUnits = context.convertToPainterUnits( mThinningSettings.minimumFeatureSize(), Qgis::RenderUnit::Millimeters );
221 if ( minPixelSizePainterUnits > 0 )
222 {
223 // calculate size in painter units of one raster pixel
224 QgsPointXY p1( rasterSubRegion.xMinimum(), rasterSubRegion.yMinimum() );
225 QgsPointXY p2( rasterSubRegion.xMinimum() + rasterSubRegion.width() / subRegionWidth,
226 rasterSubRegion.yMinimum() + rasterSubRegion.height() / subRegionHeight );
227 try
228 {
229 p1 = context.coordinateTransform().transform( p1 );
230 p2 = context.coordinateTransform().transform( p2 );
231 }
232 catch ( QgsCsException & )
233 {
234 QgsDebugError( u"Could not transform raster pixel to map crs"_s );
235 return;
236 }
237 const QgsPointXY p1PainterUnits = context.mapToPixel().transform( p1 );
238 const QgsPointXY p2PainterUnits = context.mapToPixel().transform( p2 );
239 const double painterUnitsPerRasterPixel = std::max( std::fabs( p1PainterUnits.x() - p2PainterUnits.x() ),
240 std::fabs( p1PainterUnits.y() - p2PainterUnits.y() ) ) * mResampleOver;
241 if ( painterUnitsPerRasterPixel < minPixelSizePainterUnits )
242 return;
243 }
244
245 iterator.startRasterRead( mBandNumber, subRegionWidth, subRegionHeight, rasterSubRegion, feedback );
246
247 QgsNumericFormatContext numericContext;
248 numericContext.setExpressionContext( context.expressionContext() );
249 QgsNumericFormat *numericFormat = mNumericFormat.get();
250
251 int iterLeft = 0;
252 int iterTop = 0;
253 int iterCols = 0;
254 int iterRows = 0;
255 QgsRectangle blockExtent;
256 std::unique_ptr< QgsRasterBlock > block;
257 bool isNoData = false;
258 int numberLabels = 0;
259
260 RasterProviderSettingsRestorer restorer( provider );
261 if ( mResampleOver > 1 )
262 {
263 provider->enableProviderResampling( true );
264 provider->setZoomedOutResamplingMethod( mResampleMethod );
265 provider->setMaxOversampling( mResampleOver );
266 }
267
268 while ( iterator.next( mBandNumber, iterCols, iterRows, iterLeft, iterTop, blockExtent ) )
269 {
270 if ( feedback && feedback->isCanceled() )
271 return;
272
273 const int resampledColumns = iterCols / mResampleOver;
274 const int resampledRows = iterRows / mResampleOver;
275 block.reset( provider->block( mBandNumber, blockExtent, resampledColumns, resampledRows, feedback ) );
276
277 double currentY = blockExtent.yMaximum() - 0.5 * rasterUnitsPerPixelY;
278
279 for ( int row = 0; row < resampledRows; row++ )
280 {
281 if ( feedback && feedback->isCanceled() )
282 return;
283
284 double currentX = blockExtent.xMinimum() + 0.5 * rasterUnitsPerPixelX;
285
286 for ( int column = 0; column < resampledColumns; column++ )
287 {
288 const double value = block->valueAndNoData( row, column, isNoData );
289 if ( !isNoData )
290 {
291 try
292 {
293 QgsPoint pixelCenter( currentX, currentY );
294 pixelCenter.transform( context.coordinateTransform() );
295
296 addLabel( pixelCenter,
297 numericFormat->formatDouble( value, numericContext ),
298 context );
299 numberLabels++;
300 if ( maxNumLabels > 0 && numberLabels >= maxNumLabels )
301 return;
302 }
303 catch ( QgsCsException & )
304 {
305 QgsDebugError( u"Could not transform raster pixel center to map crs"_s );
306 }
307 }
308 currentX += rasterUnitsPerPixelX;
309 }
310 currentY -= rasterUnitsPerPixelY;
311 }
312 }
313}
314
315//
316// QgsAbstractRasterLayerLabeling
317//
318
323
325{
326 return true;
327}
328
330{
331 const QString type = element.attribute( u"type"_s );
332 if ( type == "simple"_L1 )
333 {
334 return QgsRasterLayerSimpleLabeling::create( element, context );
335 }
336 else
337 {
338 return nullptr;
339 }
340}
341
342void QgsAbstractRasterLayerLabeling::toSld( QDomNode &parent, const QVariantMap &props ) const
343{
344 Q_UNUSED( parent )
345 Q_UNUSED( props )
346 QDomDocument doc = parent.ownerDocument();
347 parent.appendChild( doc.createComment( u"SE Export for %1 not implemented yet"_s.arg( type() ) ) );
348}
349
354
355//
356// QgsRasterLayerSimpleLabeling
357//
358
359
361 : mNumericFormat( std::make_unique< QgsBasicNumericFormat >() )
362{
363 mThinningSettings.setMaximumNumberLabels( 4000 );
364 mThinningSettings.setLimitNumberLabelsEnabled( true );
365 mThinningSettings.setMinimumFeatureSize( 8 );
366}
367
369
371{
372 return u"simple"_s;
373}
374
376{
377 auto res = std::make_unique< QgsRasterLayerSimpleLabeling >();
378 res->setTextFormat( mTextFormat );
379
380 if ( mNumericFormat )
381 res->mNumericFormat.reset( mNumericFormat->clone() );
382
383 res->setBand( mBandNumber );
384 res->setPriority( mPriority );
385 res->setPlacementSettings( mPlacementSettings );
386 res->setThinningSettings( mThinningSettings );
387 res->setZIndex( mZIndex );
388 res->setScaleBasedVisibility( mScaleVisibility );
389 res->setMaximumScale( mMaximumScale );
390 res->setMinimumScale( mMinimumScale );
391 res->setResampleMethod( mResampleMethod );
392 res->setResampleOver( mResampleOver );
393
394 return res.release();
395}
396
397std::unique_ptr< QgsRasterLayerLabelProvider > QgsRasterLayerSimpleLabeling::provider( QgsRasterLayer *layer ) const
398{
399 auto res = std::make_unique< QgsRasterLayerLabelProvider >( layer );
400 res->setTextFormat( mTextFormat );
401 res->setBand( mBandNumber );
402 res->setPriority( mPriority );
403 res->setPlacementSettings( mPlacementSettings );
404 res->setZIndex( mZIndex );
405 res->setThinningSettings( mThinningSettings );
406 res->setResampleMethod( mResampleMethod );
407 res->setResampleOver( mResampleOver );
408 if ( mNumericFormat )
409 {
410 res->setNumericFormat( std::unique_ptr< QgsNumericFormat >( mNumericFormat->clone() ) );
411 }
412 return res;
413}
414
415QDomElement QgsRasterLayerSimpleLabeling::save( QDomDocument &doc, const QgsReadWriteContext &context ) const
416{
417 QDomElement elem = doc.createElement( u"labeling"_s );
418 elem.setAttribute( u"type"_s, u"simple"_s );
419 elem.setAttribute( u"band"_s, mBandNumber );
420 elem.setAttribute( u"priority"_s, mPriority );
421 elem.setAttribute( u"zIndex"_s, mZIndex );
422
423 if ( mResampleOver > 1 )
424 {
425 elem.setAttribute( u"resampleOver"_s, mResampleOver );
426 }
427 elem.setAttribute( u"resampleMethod"_s, qgsEnumValueToKey( mResampleMethod ) );
428
429 {
430 QDomElement textFormatElem = doc.createElement( u"textFormat"_s );
431 textFormatElem.appendChild( mTextFormat.writeXml( doc, context ) );
432 elem.appendChild( textFormatElem );
433 }
434
435 {
436 QDomElement numericFormatElem = doc.createElement( u"numericFormat"_s );
437 mNumericFormat->writeXml( numericFormatElem, doc, context );
438 elem.appendChild( numericFormatElem );
439 }
440
441 {
442 QDomElement placementElem = doc.createElement( u"placement"_s );
443 placementElem.setAttribute( u"overlapHandling"_s, qgsEnumValueToKey( mPlacementSettings.overlapHandling() ) );
444 elem.appendChild( placementElem );
445 }
446
447 {
448 QDomElement thinningElem = doc.createElement( u"thinning"_s );
449 thinningElem.setAttribute( u"maxNumLabels"_s, mThinningSettings.maximumNumberLabels() );
450 thinningElem.setAttribute( u"limitNumLabels"_s, mThinningSettings.limitNumberOfLabelsEnabled() );
451 thinningElem.setAttribute( u"minFeatureSize"_s, mThinningSettings.minimumFeatureSize() );
452 elem.appendChild( thinningElem );
453 }
454
455 {
456 QDomElement renderingElem = doc.createElement( u"rendering"_s );
457 renderingElem.setAttribute( u"scaleVisibility"_s, mScaleVisibility );
458 // note the element names are "flipped" vs the member -- this is intentional, and done to match vector labeling
459 renderingElem.setAttribute( u"scaleMin"_s, mMaximumScale );
460 renderingElem.setAttribute( u"scaleMax"_s, mMinimumScale );
461 elem.appendChild( renderingElem );
462 }
463
464 return elem;
465}
466
468{
469 QgsStyleTextFormatEntity entity( mTextFormat );
470 if ( !visitor->visit( &entity ) )
471 return false;
472
473 return true;
474}
475
477{
478 return mTextFormat.containsAdvancedEffects();
479}
480
482{
483 return mTextFormat.hasNonDefaultCompositionMode();
484}
485
487{
488 auto res = std::make_unique< QgsRasterLayerSimpleLabeling >();
489 res->setBand( element.attribute( u"band"_s, u"1"_s ).toInt() );
490 res->setPriority( element.attribute( u"priority"_s, u"0.5"_s ).toDouble() );
491 res->setZIndex( element.attribute( u"zIndex"_s, u"0"_s ).toDouble() );
492 res->setResampleOver( element.attribute( u"resampleOver"_s, u"1"_s ).toInt() );
493 res->setResampleMethod( qgsEnumKeyToValue( element.attribute( u"resampleMethod"_s ), Qgis::RasterResamplingMethod::Average ) );
494
495 const QDomElement textFormatElem = element.firstChildElement( u"textFormat"_s );
496 if ( !textFormatElem.isNull() )
497 {
498 const QDomNodeList textFormatNodeList = textFormatElem.elementsByTagName( u"text-style"_s );
499 const QDomElement textFormatElem = textFormatNodeList.at( 0 ).toElement();
500 QgsTextFormat format;
501 format.readXml( textFormatElem, context );
502 res->setTextFormat( format );
503 }
504
505 const QDomNodeList numericFormatNodeList = element.elementsByTagName( u"numericFormat"_s );
506 if ( !numericFormatNodeList.isEmpty() )
507 {
508 const QDomElement numericFormatElem = numericFormatNodeList.at( 0 ).toElement();
509 res->mNumericFormat.reset( QgsApplication::numericFormatRegistry()->createFromXml( numericFormatElem, context ) );
510 }
511
512 QDomElement placementElem = element.firstChildElement( u"placement"_s );
513 res->mPlacementSettings.setOverlapHandling( qgsEnumKeyToValue( placementElem.attribute( u"overlapHandling"_s ), Qgis::LabelOverlapHandling::PreventOverlap ) );
514
515 QDomElement thinningElem = element.firstChildElement( u"thinning"_s );
516 res->mThinningSettings.setMaximumNumberLabels( thinningElem.attribute( u"maxNumLabels"_s, u"4000"_s ).toInt() );
517 res->mThinningSettings.setLimitNumberLabelsEnabled( thinningElem.attribute( u"limitNumLabels"_s, u"1"_s ).toInt() );
518 res->mThinningSettings.setMinimumFeatureSize( thinningElem.attribute( u"minFeatureSize"_s, u"8"_s ).toDouble() );
519
520 QDomElement renderingElem = element.firstChildElement( u"rendering"_s );
521 // note the element names are "flipped" vs the member -- this is intentional, and done to match vector labeling
522 res->mMaximumScale = renderingElem.attribute( u"scaleMin"_s, u"0"_s ).toDouble();
523 res->mMinimumScale = renderingElem.attribute( u"scaleMax"_s, u"0"_s ).toDouble();
524 res->mScaleVisibility = renderingElem.attribute( u"scaleVisibility"_s ).toInt();
525
526 return res.release();
527}
528
530{
531 return mTextFormat;
532}
533
535{
536 mTextFormat = format;
537}
538
540{
541 return mNumericFormat.get();
542}
543
545{
546 if ( format != mNumericFormat.get() )
547 mNumericFormat.reset( format );
548}
549
551{
552 return mZIndex;
553}
554
556{
557 mZIndex = index;
558}
559
561{
562 return mMaximumScale;
563}
564
566{
567 mMaximumScale = scale;
568}
569
571{
572 return mMinimumScale;
573}
574
576{
577 mMinimumScale = scale;
578}
579
581{
582 return mScaleVisibility;
583}
584
586{
587 // mMinScale (denominator!) is inclusive ( >= --> In range )
588 // mMaxScale (denominator!) is exclusive ( < --> In range )
589 return !mScaleVisibility
590 || ( ( mMinimumScale == 0 || !QgsScaleUtils::lessThanMaximumScale( scale, mMinimumScale ) )
591 && ( mMaximumScale == 0 || !QgsScaleUtils::equalToOrGreaterThanMinimumScale( scale, mMaximumScale ) ) );
592}
593
598
600{
601 mResampleMethod = method;
602}
603
605{
606 return mResampleOver;
607}
608
610{
611 mResampleOver = pixels;
612}
613
615{
616 mScaleVisibility = enabled;
617}
618
620{
621 mTextFormat.multiplyOpacity( opacityFactor );
622}
623
625{
626 auto res = std::make_unique< QgsRasterLayerSimpleLabeling >();
627 res->setTextFormat( QgsStyle::defaultTextFormatForProject( layer->project() ) );
628 res->setBand( 1 );
629 return res.release();
630}
@ OverPoint
Arranges candidates over a point (or centroid of a polygon), or at a preset offset from the point....
Definition qgis.h:1227
RasterResamplingMethod
Resampling method for raster provider-level resampling.
Definition qgis.h:1542
@ Average
Average resampling.
Definition qgis.h:1548
@ Labeling
Labeling-specific layout mode.
Definition qgis.h:2962
@ Point
Text at point of origin layout mode.
Definition qgis.h:2961
@ Horizontal
Horizontally oriented text.
Definition qgis.h:2945
@ Millimeters
Millimeters.
Definition qgis.h:5256
@ PreventOverlap
Do not allow labels to overlap other labels.
Definition qgis.h:1187
@ Reverse
Reverse/inverse transform (from destination to source).
Definition qgis.h:2731
QgsMapLayer * layer() const
Returns the associated layer, or nullptr if no layer is associated with the provider.
Flags mFlags
Flags altering drawing and registration of features.
virtual void startRender(QgsRenderContext &context)
To be called before rendering of labels begins.
Qgis::LabelPlacement mPlacement
Placement strategy.
@ DrawLabels
Whether the labels should be rendered.
QgsAbstractLabelProvider(QgsMapLayer *layer, const QString &providerId=QString())
Construct the provider with default values.
virtual QString type() const =0
Unique type string of the labeling configuration implementation.
virtual bool isInScaleRange(double scale) const
Tests whether the labels should be visible at the specified scale.
virtual bool accept(QgsStyleEntityVisitorInterface *visitor) const
Accepts the specified symbology visitor, causing it to visit all symbols associated with the labeling...
virtual void toSld(QDomNode &parent, const QVariantMap &props) const
Writes the SE 1.1 TextSymbolizer element based on the current layer labeling settings.
static QgsAbstractRasterLayerLabeling * createFromElement(const QDomElement &element, const QgsReadWriteContext &context)
Tries to create an instance of an implementation based on the XML data.
virtual void multiplyOpacity(double opacityFactor)
Multiply opacity by opacityFactor.
static QgsAbstractRasterLayerLabeling * defaultLabelingForLayer(QgsRasterLayer *layer)
Creates default labeling for a raster layer.
static QgsNumericFormatRegistry * numericFormatRegistry()
Gets the registry of available numeric formats.
A numeric formatter which returns a simple text representation of a value.
Handles coordinate transforms between two coordinate systems.
void setBallparkTransformsAreAppropriate(bool appropriate)
Sets whether approximate "ballpark" results are appropriate for this coordinate transform.
QgsPointXY transform(const QgsPointXY &point, Qgis::TransformDirection direction=Qgis::TransformDirection::Forward) const
Transform the point from the source CRS to the destination CRS.
QgsRectangle transformBoundingBox(const QgsRectangle &rectangle, Qgis::TransformDirection direction=Qgis::TransformDirection::Forward, bool handle180Crossover=false) const
Transforms a rectangle from the source CRS to the destination CRS.
Custom exception class for Coordinate Reference System related exceptions.
QString what() const
static geos::unique_ptr asGeos(const QgsGeometry &geometry, double precision=0, Qgis::GeosCreationFlags flags=Qgis::GeosCreationFlags())
Returns a geos geometry - caller takes ownership of the object (should be deleted with GEOSGeom_destr...
Definition qgsgeos.cpp:256
QgsProject * project() const
Returns the parent project if this map layer is added to a project.
Perform transforms between map coordinates and device coordinates.
void setMapRotation(double degrees, double cx, double cy)
Sets map rotation in degrees (clockwise).
double mapUnitsPerPixel() const
Returns the current map units per pixel.
QgsPointXY transform(const QgsPointXY &p) const
Transforms a point p from map (world) coordinates to device coordinates.
double mapRotation() const
Returns the current map rotation in degrees (clockwise).
static void logMessage(const QString &message, const QString &tag=QString(), Qgis::MessageLevel level=Qgis::MessageLevel::Warning, bool notifyUser=true, const char *file=__builtin_FILE(), const char *function=__builtin_FUNCTION(), int line=__builtin_LINE())
Adds a message to the log instance (and creates it if necessary).
A context for numeric formats.
void setExpressionContext(const QgsExpressionContext &context)
Sets the expression context to use when evaluating QgsExpressions.
Abstract base class for numeric formatters, which allow for formatting a numeric value for display.
Represents a 2D point.
Definition qgspointxy.h:62
double y
Definition qgspointxy.h:66
double x
Definition qgspointxy.h:65
QPointF toQPointF() const
Converts a point to a QPointF.
Definition qgspointxy.h:167
Point geometry type, with support for z-dimension and m-values.
Definition qgspoint.h:53
void transform(const QgsCoordinateTransform &ct, Qgis::TransformDirection d=Qgis::TransformDirection::Forward, bool transformZ=false) override
Transforms the geometry using a coordinate transform.
Definition qgspoint.cpp:390
Base class for raster data providers.
virtual QSize maximumTileSize() const
Returns the maximum tile size in pixels for the data provider.
virtual bool setZoomedOutResamplingMethod(Qgis::RasterResamplingMethod method)
Set resampling method to apply for zoomed-out operations.
virtual bool enableProviderResampling(bool enable)
Enable or disable provider-level resampling.
QgsRectangle extent() const override=0
Returns the extent of the layer.
virtual bool setMaxOversampling(double factor)
Sets maximum oversampling factor for zoomed-out operations.
QgsRasterBlock * block(int bandNo, const QgsRectangle &boundingBox, int width, int height, QgsRasterBlockFeedback *feedback=nullptr) override
Read block of data using given extent and size.
virtual int xSize() const
Gets raster size.
virtual int ySize() const
Iterator for sequentially processing raster cells.
void setSnapToPixelFactor(int factor)
Sets the "snap to pixel" factor in pixels.
static QgsRectangle subRegion(const QgsRectangle &rasterExtent, int rasterWidth, int rasterHeight, const QgsRectangle &subRegion, int &subRegionWidth, int &subRegionHeight, int &subRegionLeft, int &subRegionTop, int resamplingFactor=1)
Given an overall raster extent and width and height in pixels, calculates the sub region of the raste...
bool next(int bandNumber, int &columns, int &rows, int &topLeftColumn, int &topLeftRow, QgsRectangle &blockExtent)
Fetches details of the next part of the raster data.
void setMaximumTileWidth(int w)
Sets the maximum tile width returned during iteration.
void startRasterRead(int bandNumber, qgssize nCols, qgssize nRows, const QgsRectangle &extent, QgsRasterBlockFeedback *feedback=nullptr)
Start reading of raster band.
void setMaximumTileHeight(int h)
Sets the minimum tile height returned during iteration.
void setTextFormat(const QgsTextFormat &format)
Sets the text format used for rendering the labels.
QgsRasterLayerLabelProvider(QgsRasterLayer *layer)
Constructor for QgsRasterLayerLabelProvider.
void setResampleMethod(Qgis::RasterResamplingMethod method)
Sets the resampling method to use when the raster labels are being resampled over neighboring pixels.
void addLabel(const QgsPoint &mapPoint, const QString &text, QgsRenderContext &context)
Adds a label at the specified point in map coordinates.
QgsNumericFormat * numericFormat()
Returns the numeric format to be used for the labels.
void generateLabels(QgsRenderContext &context, QgsRasterPipe *pipe, QgsRasterViewPort *rasterViewPort, QgsRasterLayerRendererFeedback *feedback)
Generates the labels, given a render context and input pipe.
void drawLabel(QgsRenderContext &context, pal::LabelPosition *label) const final
Draw this label at the position determined by the labeling engine.
QList< QgsLabelFeature * > labelFeatures(QgsRenderContext &) final
Returns list of label features (they are owned by the provider and thus deleted on its destruction).
void setNumericFormat(std::unique_ptr< QgsNumericFormat > format)
Sets the numeric format used for the labels.
void startRender(QgsRenderContext &context) final
To be called before rendering of labels begins.
void setResampleOver(int pixels)
Sets the number of neighboring pixels to resample over, when labels are showing values resampled over...
double maximumScale() const
Returns the maximum map scale (i.e.
int resampleOver() const
Returns the number of neighboring pixels to resample over, when labels are showing values resampled o...
void setTextFormat(const QgsTextFormat &format)
Sets the text format used for rendering the labels.
double zIndex() const
Returns the Z-Index of the labels.
double minimumScale() const
Returns the minimum map scale (i.e.
bool hasScaleBasedVisibility() const
Returns whether scale based visibility is enabled for the labels.
static QgsRasterLayerSimpleLabeling * create(const QDomElement &element, const QgsReadWriteContext &context)
Creates a QgsRasterLayerSimpleLabeling from a DOM element with saved configuration.
void setScaleBasedVisibility(bool enabled)
Sets whether scale based visibility is enabled for the labels.
void setResampleMethod(Qgis::RasterResamplingMethod method)
Sets the resampling method to use when the raster labels are being resampled over neighboring pixels.
void setMinimumScale(double scale)
Sets the minimum map scale (i.e.
void setNumericFormat(QgsNumericFormat *format)
Sets the numeric format used for the labels.
~QgsRasterLayerSimpleLabeling() override
bool accept(QgsStyleEntityVisitorInterface *visitor) const override
Accepts the specified symbology visitor, causing it to visit all symbols associated with the labeling...
std::unique_ptr< QgsRasterLayerLabelProvider > provider(QgsRasterLayer *layer) const override
Creates a raster label provider corresponding to this object's configuration.
QgsTextFormat textFormat() const
Returns the text format used for rendering the labels.
bool isInScaleRange(double scale) const override
Tests whether the labels should be visible at the specified scale.
void setMaximumScale(double scale)
Sets the maximum map scale (i.e.
Qgis::RasterResamplingMethod resampleMethod() const
Returns the resampling method used when the raster labels are being resampled over neighboring pixels...
void setResampleOver(int pixels)
Sets the number of neighboring pixels to resample over, when labels are showing values resampled over...
void multiplyOpacity(double opacityFactor) override
Multiply opacity by opacityFactor.
QString type() const override
Unique type string of the labeling configuration implementation.
QDomElement save(QDomDocument &doc, const QgsReadWriteContext &context) const override
Saves the labeling configuration to an XML element.
QgsRasterLayerSimpleLabeling * clone() const override
Returns a new copy of the object.
bool hasNonDefaultCompositionMode() const override
Returns true the labeling requires a non-default composition mode.
const QgsNumericFormat * numericFormat() const
Returns the numeric format used for the labels.
bool requiresAdvancedEffects() const override
Returns true if drawing labels requires advanced effects like composition modes, which could prevent ...
void setZIndex(double index)
Sets the Z-Index of the labels.
Represents a raster layer.
Contains a pipeline of raster interfaces for sequential raster processing.
QgsRasterDataProvider * provider() const
Returns the data provider interface, or nullptr if no data provider is present in the pipe.
A container for the context for various read/write operations on objects.
A rectangle specified with double values.
double xMinimum
double yMinimum
double yMaximum
QgsPointXY center
Contains information about the context of a rendering operation.
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).
QgsExpressionContext & expressionContext()
Gets the expression context.
QgsRectangle mapExtent() const
Returns the original extent of the map being rendered.
const QgsMapToPixel & mapToPixel() const
Returns the context's map to pixel transform, which transforms between map coordinates and device coo...
QgsCoordinateTransform coordinateTransform() const
Returns the current coordinate transform for the context.
static bool equalToOrGreaterThanMinimumScale(const double scale, const double minScale)
Returns whether the scale is equal to or greater than the minScale, taking non-round numbers into acc...
static bool lessThanMaximumScale(const double scale, const double maxScale)
Returns whether the scale is less than the maxScale, taking non-round numbers into account.
An interface for classes which can visit style entity (e.g.
virtual bool visit(const QgsStyleEntityVisitorInterface::StyleLeaf &entity)
Called when the visitor will visit a style entity.
A text format entity for QgsStyle databases.
Definition qgsstyle.h:1461
static QgsTextFormat defaultTextFormatForProject(QgsProject *project, QgsStyle::TextFormatContext context=QgsStyle::TextFormatContext::Labeling)
Returns the default text format to use for new text based objects for the specified project,...
Contains pre-calculated metrics of a QgsTextDocument.
QSizeF documentSize(Qgis::TextLayoutMode mode, Qgis::TextOrientation orientation) const
Returns the overall size of the document.
static QgsTextDocumentMetrics calculateMetrics(const QgsTextDocument &document, const QgsTextFormat &format, const QgsRenderContext &context, double scaleFactor=1.0, const QgsTextDocumentRenderContext &documentContext=QgsTextDocumentRenderContext())
Returns precalculated text metrics for a text document, when rendered using the given base format and...
Represents a document consisting of one or more QgsTextBlock objects.
static QgsTextDocument fromTextAndFormat(const QStringList &lines, const QgsTextFormat &format)
Constructor for QgsTextDocument consisting of a set of lines, respecting settings from a text format.
Container for all settings relating to text rendering.
void readXml(const QDomElement &elem, const QgsReadWriteContext &context)
Read settings from a DOM element.
Adds extra information to QgsLabelFeature for text labels.
const QgsTextDocumentMetrics & documentMetrics() const
Returns the document metrics for the label.
const QgsTextDocument & document() const
Returns the document for the label.
static void drawDocument(const QRectF &rect, const QgsTextFormat &format, const QgsTextDocument &document, const QgsTextDocumentMetrics &metrics, QgsRenderContext &context, Qgis::TextHorizontalAlignment horizontalAlignment=Qgis::TextHorizontalAlignment::Left, Qgis::TextVerticalAlignment verticalAlignment=Qgis::TextVerticalAlignment::Top, double rotation=0, Qgis::TextLayoutMode mode=Qgis::TextLayoutMode::Rectangle, Qgis::TextRendererFlags flags=Qgis::TextRendererFlags())
Draws a text document within a rectangle using the specified settings.
QgsLabelFeature * feature()
Returns the parent feature.
Definition feature.h:89
LabelPosition is a candidate feature label position.
double getAlpha() const
Returns the angle to rotate text (in radians).
FeaturePart * getFeaturePart() const
Returns the feature corresponding to this labelposition.
double getX(int i=0) const
Returns the down-left x coordinate.
double getY(int i=0) const
Returns the down-left y coordinate.
T qgsEnumKeyToValue(const QString &key, const T &defaultValue, bool tryValueAsKey=true, bool *returnOk=nullptr)
Returns the value corresponding to the given key of an enum.
Definition qgis.h:7110
QString qgsEnumValueToKey(const T &value, bool *returnOk=nullptr)
Returns the value for the given key of an enum.
Definition qgis.h:7091
bool qgsDoubleNear(double a, double b, double epsilon=4 *std::numeric_limits< double >::epsilon())
Compare two doubles (but allow some difference).
Definition qgis.h:6900
#define QgsDebugError(str)
Definition qgslogger.h:59
This class provides details of the viewable area that a raster will be rendered into.
QgsRectangle mDrawnExtent
Intersection of current map extent and layer extent, in map (destination) CRS.