QGIS API Documentation 3.41.0-Master (45a0abf3bec)
Loading...
Searching...
No Matches
qgstextrenderer.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgstextrenderer.cpp
3 -------------------
4 begin : September 2015
5 copyright : (C) Nyall Dawson
6 email : nyall dot dawson 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 "qgstextrenderer.h"
17#include "qgstextformat.h"
18#include "qgstextdocument.h"
20#include "qgstextfragment.h"
21#include "qgspallabeling.h"
22#include "qgspainteffect.h"
23#include "qgspainterswapper.h"
25#include "qgssymbollayerutils.h"
26#include "qgsmarkersymbol.h"
27#include "qgsfillsymbol.h"
28#include "qgsunittypes.h"
29#include "qgstextmetrics.h"
31#include "qgsgeos.h"
32#include "qgspainting.h"
33#include "qgsapplication.h"
34#include "qgsimagecache.h"
35#include <optional>
36
37#include <QTextBoundaryFinder>
38
39
41{
42 if ( alignment & Qt::AlignLeft )
44 else if ( alignment & Qt::AlignRight )
46 else if ( alignment & Qt::AlignHCenter )
48 else if ( alignment & Qt::AlignJustify )
50
51 // not supported?
53}
54
56{
57 if ( alignment & Qt::AlignTop )
59 else if ( alignment & Qt::AlignBottom )
61 else if ( alignment & Qt::AlignVCenter )
63 //not supported
64 else if ( alignment & Qt::AlignBaseline )
66
68}
69
70int QgsTextRenderer::sizeToPixel( double size, const QgsRenderContext &c, Qgis::RenderUnit unit, const QgsMapUnitScale &mapUnitScale )
71{
72 return static_cast< int >( c.convertToPainterUnits( size, unit, mapUnitScale ) + 0.5 ); //NOLINT
73}
74
75void QgsTextRenderer::drawText( const QRectF &rect, double rotation, Qgis::TextHorizontalAlignment alignment, const QStringList &text, QgsRenderContext &context, const QgsTextFormat &_format, bool, Qgis::TextVerticalAlignment vAlignment, Qgis::TextRendererFlags flags,
77{
78 QgsTextFormat lFormat = _format;
79 if ( _format.dataDefinedProperties().hasActiveProperties() ) // note, we use format instead of tmpFormat here, it's const and potentially avoids a detach
80 lFormat.updateDataDefinedProperties( context );
81
82 // DO NOT USE _format in the following code, always use lFormat!!
83 QgsTextDocumentRenderContext documentContext;
84 documentContext.setFlags( flags );
85 documentContext.setMaximumWidth( rect.width() );
86
87 const QgsTextDocument document = QgsTextDocument::fromTextAndFormat( text, lFormat );
88
89 const double fontScale = calculateScaleFactorForFormat( context, lFormat );
90 const QgsTextDocumentMetrics metrics = QgsTextDocumentMetrics::calculateMetrics( document, lFormat, context, fontScale, documentContext );
91
92 drawDocument( rect, lFormat, metrics.document(), metrics, context, alignment, vAlignment, rotation, mode, flags );
93}
94
95void QgsTextRenderer::drawDocument( const QRectF &rect, const QgsTextFormat &format, const QgsTextDocument &document, const QgsTextDocumentMetrics &metrics, QgsRenderContext &context, Qgis::TextHorizontalAlignment horizontalAlignment, Qgis::TextVerticalAlignment verticalAlignment, double rotation, Qgis::TextLayoutMode mode, Qgis::TextRendererFlags )
96{
97 const QgsTextFormat tmpFormat = updateShadowPosition( format );
98
100 if ( tmpFormat.background().enabled() )
101 {
103 }
104
105 if ( tmpFormat.shadow().enabled() )
106 {
107 components |= Qgis::TextComponent::Shadow;
108 }
109
110 if ( tmpFormat.buffer().enabled() )
111 {
112 components |= Qgis::TextComponent::Buffer;
113 }
114
115 drawParts( rect, rotation, horizontalAlignment, verticalAlignment, document, metrics, context, tmpFormat, components, mode );
116}
117
118void QgsTextRenderer::drawText( QPointF point, double rotation, Qgis::TextHorizontalAlignment alignment, const QStringList &textLines, QgsRenderContext &context, const QgsTextFormat &_format, bool )
119{
120 QgsTextFormat lFormat = _format;
121 if ( _format.dataDefinedProperties().hasActiveProperties() ) // note, we use _format instead of tmpFormat here, it's const and potentially avoids a detach
122 lFormat.updateDataDefinedProperties( context );
123 lFormat = updateShadowPosition( lFormat );
124
125 // DO NOT USE _format in the following code, always use lFormat!!
126 const QgsTextDocument document = QgsTextDocument::fromTextAndFormat( textLines, lFormat );
127 const double fontScale = calculateScaleFactorForFormat( context, lFormat );
128 const QgsTextDocumentMetrics metrics = QgsTextDocumentMetrics::calculateMetrics( document, lFormat, context, fontScale );
129
130 drawDocument( point, lFormat, metrics.document(), metrics, context, alignment, rotation );
131}
132
133void QgsTextRenderer::drawDocument( QPointF point, const QgsTextFormat &format, const QgsTextDocument &document, const QgsTextDocumentMetrics &metrics, QgsRenderContext &context, Qgis::TextHorizontalAlignment alignment, double rotation )
134{
136 if ( format.background().enabled() )
137 {
139 }
140
141 if ( format.shadow().enabled() )
142 {
143 components |= Qgis::TextComponent::Shadow;
144 }
145
146 if ( format.buffer().enabled() )
147 {
148 components |= Qgis::TextComponent::Buffer;
149 }
150
151 drawParts( point, rotation, alignment, document, metrics, context, format, components, Qgis::TextLayoutMode::Point );
152}
153
154void QgsTextRenderer::drawTextOnLine( const QPolygonF &line, const QString &text, QgsRenderContext &context, const QgsTextFormat &_format, double offsetAlongLine, double offsetFromLine )
155{
156 QgsTextFormat lFormat = _format;
157 if ( _format.dataDefinedProperties().hasActiveProperties() ) // note, we use _format instead of tmpFormat here, it's const and potentially avoids a detach
158 lFormat.updateDataDefinedProperties( context );
159 lFormat = updateShadowPosition( lFormat );
160
161 // DO NOT USE _format in the following code, always use lFormat!!
162
163 // todo handle newlines??
164 const QgsTextDocument document = QgsTextDocument::fromTextAndFormat( {text}, lFormat );
165
166 drawDocumentOnLine( line, lFormat, document, context, offsetAlongLine, offsetFromLine );
167}
168
169void QgsTextRenderer::drawDocumentOnLine( const QPolygonF &line, const QgsTextFormat &format, const QgsTextDocument &document, QgsRenderContext &context, double offsetAlongLine, double offsetFromLine )
170{
171 QPolygonF labelBaselineCurve = line;
172 if ( !qgsDoubleNear( offsetFromLine, 0 ) )
173 {
174 std::unique_ptr < QgsLineString > ring( QgsLineString::fromQPolygonF( line ) );
175 QgsGeos geos( ring.get() );
176 std::unique_ptr < QgsLineString > offsetCurve( dynamic_cast< QgsLineString * >( geos.offsetCurve( offsetFromLine, 4, Qgis::JoinStyle::Round, 2 ) ) );
177 if ( !offsetCurve )
178 return;
179
180#if GEOS_VERSION_MAJOR==3 && GEOS_VERSION_MINOR<11
181 if ( offsetFromLine < 0 )
182 {
183 // geos < 3.11 reverses the direction of offset curves with negative distances -- we don't want that!
184 std::unique_ptr < QgsLineString > reversed( offsetCurve->reversed() );
185 if ( !reversed )
186 return;
187
188 offsetCurve = std::move( reversed );
189 }
190#endif
191
192 labelBaselineCurve = offsetCurve->asQPolygonF();
193 }
194
195 const double fontScale = calculateScaleFactorForFormat( context, format );
196
197 const QFont baseFont = format.scaledFont( context, fontScale );
198 const double letterSpacing = baseFont.letterSpacing() / fontScale;
199 const double wordSpacing = baseFont.wordSpacing() / fontScale;
200
201 QStringList graphemes;
202 QVector< QgsTextCharacterFormat > graphemeFormats;
203 QVector< QgsTextDocumentMetrics > graphemeMetrics;
204
205 for ( const QgsTextBlock &block : std::as_const( document ) )
206 {
207 for ( const QgsTextFragment &fragment : block )
208 {
209 const QStringList fragmentGraphemes = QgsPalLabeling::splitToGraphemes( fragment.text() );
210 for ( const QString &grapheme : fragmentGraphemes )
211 {
212 graphemes.append( grapheme );
213 graphemeFormats.append( fragment.characterFormat() );
214
215 QgsTextDocument document;
216 document.append( QgsTextBlock( QgsTextFragment( grapheme, fragment.characterFormat() ) ) );
217
218 graphemeMetrics.append( QgsTextDocumentMetrics::calculateMetrics( document, format, context, fontScale ) );
219 }
220 }
221 }
222
223 QVector< double > characterWidths( graphemes.count() );
224 QVector< double > characterHeights( graphemes.count() );
225 QVector< double > characterDescents( graphemes.count() );
226 QFont previousNonSuperSubScriptFont;
227
228 for ( int i = 0; i < graphemes.count(); i++ )
229 {
230 // reconstruct how Qt creates word spacing, then adjust per individual stored character
231 // this will allow the text renderer to create each candidate width = character width + correct spacing
232
233 double graphemeFirstCharHorizontalAdvanceWithLetterSpacing = 0;
234 double graphemeFirstCharHorizontalAdvance = 0;
235 double graphemeHorizontalAdvance = 0;
236 double characterDescent = 0;
237 double characterHeight = 0;
238 const QgsTextCharacterFormat *graphemeFormat = &graphemeFormats[i];
239
240 QFont graphemeFont = baseFont;
241 graphemeFormat->updateFontForFormat( graphemeFont, context, fontScale );
242
243 if ( i == 0 )
244 previousNonSuperSubScriptFont = graphemeFont;
245
246 if ( graphemeFormat->hasVerticalAlignmentSet() )
247 {
248 switch ( graphemeFormat->verticalAlignment() )
249 {
251 previousNonSuperSubScriptFont = graphemeFont;
252 break;
253
256 {
257 if ( graphemeFormat->fontPointSize() < 0 )
258 {
259 // if fragment has no explicit font size set, then we scale the inherited font size to 60% of base font size
260 // this allows for easier use of super/subscript in labels as "my text<sup>2</sup>" will automatically render
261 // the superscript in a smaller font size. BUT if the fragment format HAS a non -1 font size then it indicates
262 // that the document has an explicit font size for the super/subscript element, eg "my text<sup style="font-size: 6pt">2</sup>"
263 // which we should respect
264 graphemeFont.setPixelSize( static_cast< int >( std::round( graphemeFont.pixelSize() * SUPERSCRIPT_SUBSCRIPT_FONT_SIZE_SCALING_FACTOR ) ) );
265 }
266 break;
267 }
268 }
269 }
270 else
271 {
272 previousNonSuperSubScriptFont = graphemeFont;
273 }
274
275 const QFontMetricsF graphemeFontMetrics( graphemeFont );
276 graphemeFirstCharHorizontalAdvance = graphemeFontMetrics.horizontalAdvance( QString( graphemes[i].at( 0 ) ) ) / fontScale;
277 graphemeFirstCharHorizontalAdvanceWithLetterSpacing = graphemeFontMetrics.horizontalAdvance( graphemes[i].at( 0 ) ) / fontScale + letterSpacing;
278 graphemeHorizontalAdvance = graphemeFontMetrics.horizontalAdvance( QString( graphemes[i] ) ) / fontScale;
279 characterDescent = graphemeFontMetrics.descent() / fontScale;
280 characterHeight = graphemeFontMetrics.height() / fontScale;
281
282 qreal wordSpaceFix = qreal( 0.0 );
283 if ( graphemes[i] == QLatin1String( " " ) )
284 {
285 // word spacing only gets added once at end of consecutive run of spaces, see QTextEngine::shapeText()
286 int nxt = i + 1;
287 wordSpaceFix = ( nxt < graphemes.count() && graphemes[nxt] != QLatin1String( " " ) ) ? wordSpacing : qreal( 0.0 );
288 }
289
290 // this workaround only works for clusters with a single character. Not sure how it should be handled
291 // with multi-character clusters.
292 if ( graphemes[i].length() == 1 &&
293 !qgsDoubleNear( graphemeFirstCharHorizontalAdvance, graphemeFirstCharHorizontalAdvanceWithLetterSpacing ) )
294 {
295 // word spacing applied when it shouldn't be
296 wordSpaceFix -= wordSpacing;
297 }
298
299 const double charWidth = graphemeHorizontalAdvance + wordSpaceFix;
300 characterWidths[i] = charWidth;
301 characterHeights[i] = characterHeight;
302 characterDescents[i] = characterDescent;
303 }
304
305 QgsPrecalculatedTextMetrics metrics( graphemes, std::move( characterWidths ), std::move( characterHeights ), std::move( characterDescents ) );
306 metrics.setGraphemeFormats( graphemeFormats );
307
308 std::unique_ptr< QgsTextRendererUtils::CurvePlacementProperties > placement = QgsTextRendererUtils::generateCurvedTextPlacement(
309 metrics, labelBaselineCurve, offsetAlongLine,
311 -1, -1,
314 );
315
316 if ( placement->graphemePlacement.empty() )
317 return;
318
319 // We may have deliberately skipped over some graphemes during curved text placement (such as zero-width graphemes).
320 // So we need to use a hash of the original grapheme index to place generated components in, as there may accordingly
321 // be graphemes which don't result in components, and we can't just blindly assume the component array position
322 // will match the original grapheme index
323 QHash< int, QgsTextRenderer::Component > components;
324 components.reserve( placement->graphemePlacement.size() );
325 for ( const QgsTextRendererUtils::CurvedGraphemePlacement &grapheme : std::as_const( placement->graphemePlacement ) )
326 {
327 QgsTextRenderer::Component component;
328 component.origin = QPointF( grapheme.x, grapheme.y );
329 component.rotation = -grapheme.angle;
330
331 QgsTextDocumentMetrics &metrics = graphemeMetrics[ grapheme.graphemeIndex ];
332 const double verticalOffset = metrics.fragmentVerticalOffset( 0, 0, Qgis::TextLayoutMode::Point );
333 if ( !qgsDoubleNear( verticalOffset, 0 ) )
334 {
335 component.origin.rx() += verticalOffset * std::cos( grapheme.angle + M_PI_2 );
336 component.origin.ry() += verticalOffset * std::sin( grapheme.angle + M_PI_2 );
337 }
338
339 components.insert( grapheme.graphemeIndex, component );
340 }
341
342 if ( format.background().enabled() )
343 {
344 for ( const QgsTextRendererUtils::CurvedGraphemePlacement &grapheme : std::as_const( placement->graphemePlacement ) )
345 {
346 const QgsTextDocumentMetrics &metrics = graphemeMetrics.at( grapheme.graphemeIndex );
347 const QgsTextRenderer::Component &component = components[grapheme.graphemeIndex ];
348 drawBackground( context, component, format, metrics, Qgis::TextLayoutMode::Point );
349 }
350 }
351
352 if ( format.buffer().enabled() )
353 {
354 for ( const QgsTextRendererUtils::CurvedGraphemePlacement &grapheme : std::as_const( placement->graphemePlacement ) )
355 {
356 const QgsTextDocumentMetrics &metrics = graphemeMetrics.at( grapheme.graphemeIndex );
357 const QgsTextRenderer::Component &component = components[grapheme.graphemeIndex ];
358
359 drawTextInternal( Qgis::TextComponent::Buffer,
360 context,
361 format,
362 component,
363 metrics.document(),
364 metrics,
368 }
369 }
370
371 for ( const QgsTextRendererUtils::CurvedGraphemePlacement &grapheme : std::as_const( placement->graphemePlacement ) )
372 {
373 const QgsTextDocumentMetrics &metrics = graphemeMetrics.at( grapheme.graphemeIndex );
374 const QgsTextRenderer::Component &component = components[grapheme.graphemeIndex ];
375
376 drawTextInternal( Qgis::TextComponent::Text,
377 context,
378 format,
379 component,
380 metrics.document(),
381 metrics,
385 }
386}
387
388QgsTextFormat QgsTextRenderer::updateShadowPosition( const QgsTextFormat &format )
389{
391 return format;
392
393 QgsTextFormat tmpFormat = format;
394 if ( tmpFormat.background().enabled() && tmpFormat.background().type() != QgsTextBackgroundSettings::ShapeMarkerSymbol ) // background shadow not compatible with marker symbol backgrounds
395 {
397 }
398 else if ( tmpFormat.buffer().enabled() )
399 {
401 }
402 else
403 {
405 }
406 return tmpFormat;
407}
408
409void QgsTextRenderer::drawPart( const QRectF &rect, double rotation, Qgis::TextHorizontalAlignment alignment,
410 const QStringList &textLines, QgsRenderContext &context, const QgsTextFormat &format, Qgis::TextComponent part, bool )
411{
412 const QgsTextDocument document = QgsTextDocument::fromTextAndFormat( textLines, format );
413 const double fontScale = calculateScaleFactorForFormat( context, format );
414 const QgsTextDocumentMetrics metrics = QgsTextDocumentMetrics::calculateMetrics( document, format, context, fontScale );
415
416 drawParts( rect, rotation, alignment, Qgis::TextVerticalAlignment::Top, metrics.document(), metrics, context, format, part, Qgis::TextLayoutMode::Rectangle );
417}
418
419void QgsTextRenderer::drawParts( const QRectF &rect, double rotation, Qgis::TextHorizontalAlignment alignment, Qgis::TextVerticalAlignment vAlignment, const QgsTextDocument &document, const QgsTextDocumentMetrics &metrics, QgsRenderContext &context, const QgsTextFormat &format, Qgis::TextComponents parts, Qgis::TextLayoutMode mode )
420{
421 if ( !context.painter() )
422 {
423 return;
424 }
425
426 Component component;
427 component.dpiRatio = 1.0;
428 component.origin = rect.topLeft();
429 component.rotation = rotation;
430 component.size = rect.size();
431 component.hAlign = alignment;
432
433 if ( ( parts & Qgis::TextComponent::Background ) && format.background().enabled() )
434 {
435 if ( !qgsDoubleNear( rotation, 0.0 ) )
436 {
437 // get rotated label's center point
438
439 double xc = rect.width() / 2.0;
440 double yc = rect.height() / 2.0;
441
442 double angle = -rotation;
443 double xd = xc * std::cos( angle ) - yc * std::sin( angle );
444 double yd = xc * std::sin( angle ) + yc * std::cos( angle );
445
446 component.center = QPointF( component.origin.x() + xd, component.origin.y() + yd );
447 }
448 else
449 {
450 component.center = rect.center();
451 }
452
453 switch ( vAlignment )
454 {
456 break;
458 component.origin.ry() += ( rect.height() - metrics.documentSize( mode, format.orientation() ).height() ) / 2;
459 break;
461 component.origin.ry() += ( rect.height() - metrics.documentSize( mode, format.orientation() ).height() );
462 break;
463 }
464
465 QgsTextRenderer::drawBackground( context, component, format, metrics, Qgis::TextLayoutMode::Rectangle );
466 }
467
468 if ( parts == Qgis::TextComponents( Qgis::TextComponent::Buffer ) && !format.buffer().enabled() )
469 {
470 return;
471 }
472
474 {
475 drawTextInternal( parts, context, format, component,
476 document, metrics,
477 alignment, vAlignment, mode );
478 }
479}
480
481void QgsTextRenderer::drawPart( QPointF origin, double rotation, Qgis::TextHorizontalAlignment alignment, const QStringList &textLines, QgsRenderContext &context, const QgsTextFormat &format, Qgis::TextComponent part, bool )
482{
483 const QgsTextDocument document = QgsTextDocument::fromTextAndFormat( textLines, format );
484 const double fontScale = calculateScaleFactorForFormat( context, format );
485 const QgsTextDocumentMetrics metrics = QgsTextDocumentMetrics::calculateMetrics( document, format, context, fontScale );
486
487 drawParts( origin, rotation, alignment, metrics.document(), metrics, context, format, part, Qgis::TextLayoutMode::Point );
488}
489
490void QgsTextRenderer::drawParts( QPointF origin, double rotation, Qgis::TextHorizontalAlignment alignment, const QgsTextDocument &document, const QgsTextDocumentMetrics &metrics, QgsRenderContext &context, const QgsTextFormat &format, Qgis::TextComponents parts, Qgis::TextLayoutMode mode )
491{
492 if ( !context.painter() )
493 {
494 return;
495 }
496
497 Component component;
498 component.dpiRatio = 1.0;
499 component.origin = origin;
500 component.rotation = rotation;
501 component.hAlign = alignment;
502
503 if ( ( parts & Qgis::TextComponent::Background ) && format.background().enabled() )
504 {
505 QgsTextRenderer::drawBackground( context, component, format, metrics, mode );
506 }
507
508 if ( parts == Qgis::TextComponents( Qgis::TextComponent::Buffer ) && !format.buffer().enabled() )
509 {
510 return;
511 }
512
514 {
515 drawTextInternal( parts, context, format, component,
516 document,
517 metrics,
519 mode );
520 }
521}
522
523QFontMetricsF QgsTextRenderer::fontMetrics( QgsRenderContext &context, const QgsTextFormat &format, const double scaleFactor )
524{
525 return QFontMetricsF( format.scaledFont( context, scaleFactor ), context.painter() ? context.painter()->device() : nullptr );
526}
527
528double QgsTextRenderer::drawBuffer( QgsRenderContext &context, const QgsTextRenderer::Component &component, const QgsTextFormat &format,
529 const QgsTextDocumentMetrics &metrics,
531{
532 QPainter *p = context.painter();
533
534 Qgis::TextOrientation orientation = format.orientation();
536 {
537 if ( component.rotation >= -315 && component.rotation < -90 )
538 {
540 }
541 else if ( component.rotation >= -90 && component.rotation < -45 )
542 {
544 }
545 else
546 {
548 }
549 }
550
551 QgsTextBufferSettings buffer = format.buffer();
552
553 const double penSize = buffer.sizeUnit() == Qgis::RenderUnit::Percentage
554 ? context.convertToPainterUnits( format.size(), format.sizeUnit(), format.sizeMapUnitScale() ) * buffer.size() / 100
555 : context.convertToPainterUnits( buffer.size(), buffer.sizeUnit(), buffer.sizeMapUnitScale() );
556
557 const double scaleFactor = calculateScaleFactorForFormat( context, format );
558
559 std::optional< QgsScopedRenderContextReferenceScaleOverride > referenceScaleOverride;
560 if ( mode == Qgis::TextLayoutMode::Labeling )
561 {
562 // label size has already been calculated using any symbology reference scale factor -- we need
563 // to temporarily remove the reference scale here or we'll be applying the scaling twice
564 referenceScaleOverride.emplace( QgsScopedRenderContextReferenceScaleOverride( context, -1.0 ) );
565 }
566
567 if ( metrics.isNullFontSize() )
568 return 0;
569
570 referenceScaleOverride.reset();
571
572 QPainterPath path;
573 path.setFillRule( Qt::WindingFill );
574 double advance = 0;
575 double height = component.size.height();
576 switch ( orientation )
577 {
579 {
580 // NOT SUPPORTED BY THIS METHOD ANYMORE -- buffer drawing is handled in drawTextInternalHorizontal since QGIS 3.42
581 break;
582 }
583
586 {
587 double partYOffset = component.offset.y() * scaleFactor;
588
589 const double blockMaximumCharacterWidth = metrics.blockMaximumCharacterWidth( component.blockIndex );
590 double partLastDescent = 0;
591
592 int fragmentIndex = 0;
593 for ( const QgsTextFragment &fragment : component.block )
594 {
595 const QFont fragmentFont = metrics.fragmentFont( component.blockIndex, component.firstFragmentIndex + fragmentIndex );
596 const double letterSpacing = fragmentFont.letterSpacing() / scaleFactor;
597
598 const QFontMetricsF fragmentMetrics( fragmentFont );
599
600 const double fragmentYOffset = metrics.fragmentVerticalOffset( component.blockIndex, fragmentIndex, mode );
601
602 const QStringList parts = QgsPalLabeling::splitToGraphemes( fragment.text() );
603 for ( const QString &part : parts )
604 {
605 double partXOffset = ( blockMaximumCharacterWidth - ( fragmentMetrics.horizontalAdvance( part ) / scaleFactor - letterSpacing ) ) / 2;
606 partYOffset += fragmentMetrics.ascent() / scaleFactor;
607 path.addText( partXOffset, partYOffset + fragmentYOffset, fragmentFont, part );
608 partYOffset += letterSpacing;
609 }
610 partLastDescent = fragmentMetrics.descent() / scaleFactor;
611
612 fragmentIndex++;
613 }
614 height = partYOffset + partLastDescent;
615 advance = partYOffset - component.offset.y() * scaleFactor;
616 break;
617 }
618 }
619
620 QColor bufferColor = buffer.color();
621 bufferColor.setAlphaF( buffer.opacity() );
622 QPen pen( bufferColor );
623 pen.setWidthF( penSize * scaleFactor );
624 pen.setJoinStyle( buffer.joinStyle() );
625 QColor tmpColor( bufferColor );
626 // honor pref for whether to fill buffer interior
627 if ( !buffer.fillBufferInterior() )
628 {
629 tmpColor.setAlpha( 0 );
630 }
631
632 // store buffer's drawing in QPicture for drop shadow call
633 QPicture buffPict;
634 QPainter buffp;
635 buffp.begin( &buffPict );
636 if ( buffer.paintEffect() && buffer.paintEffect()->enabled() )
637 {
638 context.setPainter( &buffp );
639 std::unique_ptr< QgsPaintEffect > tmpEffect( buffer.paintEffect()->clone() );
640
641 tmpEffect->begin( context );
642 context.painter()->setPen( pen );
643 context.painter()->setBrush( tmpColor );
644 if ( scaleFactor != 1.0 )
645 context.painter()->scale( 1 / scaleFactor, 1 / scaleFactor );
646 context.painter()->drawPath( path );
647 if ( scaleFactor != 1.0 )
648 context.painter()->scale( scaleFactor, scaleFactor );
649 tmpEffect->end( context );
650
651 context.setPainter( p );
652 }
653 else
654 {
655 if ( scaleFactor != 1.0 )
656 buffp.scale( 1 / scaleFactor, 1 / scaleFactor );
657 buffp.setPen( pen );
658 buffp.setBrush( tmpColor );
659 buffp.drawPath( path );
660 }
661 buffp.end();
662
664 {
665 QgsTextRenderer::Component bufferComponent = component;
666 bufferComponent.origin = QPointF( 0.0, 0.0 );
667 bufferComponent.picture = buffPict;
668 bufferComponent.pictureBuffer = penSize / 2.0;
669 bufferComponent.size.setHeight( height );
670
672 {
673 bufferComponent.offset.setY( - bufferComponent.size.height() );
674 }
675 drawShadow( context, bufferComponent, format );
676 }
677
678 QgsScopedQPainterState painterState( p );
679 context.setPainterFlagsUsingContext( p );
680
681 if ( context.useAdvancedEffects() )
682 {
683 p->setCompositionMode( buffer.blendMode() );
684 }
685
686 // scale for any print output or image saving @ specific dpi
687 p->scale( component.dpiRatio, component.dpiRatio );
689 p->drawPicture( 0, 0, buffPict );
690
691 return advance / scaleFactor;
692}
693
694void QgsTextRenderer::drawMask( QgsRenderContext &context, const QgsTextRenderer::Component &component, const QgsTextFormat &format, const QgsTextDocumentMetrics &metrics,
696{
697 QgsTextMaskSettings mask = format.mask();
698
699 // the mask is drawn to a side painter
700 // or to the main painter for preview
701 QPainter *p = context.isGuiPreview() ? context.painter() : context.maskPainter( context.currentMaskId() );
702 if ( ! p )
703 return;
704
705 double penSize = mask.sizeUnit() == Qgis::RenderUnit::Percentage
706 ? context.convertToPainterUnits( format.size(), format.sizeUnit(), format.sizeMapUnitScale() ) * mask.size() / 100
707 : context.convertToPainterUnits( mask.size(), mask.sizeUnit(), mask.sizeMapUnitScale() );
708
709 // buffer: draw the text with a big pen
710 QPainterPath path;
711 path.setFillRule( Qt::WindingFill );
712
713 const double scaleFactor = calculateScaleFactorForFormat( context, format );
714
715 // TODO: vertical text mode was ignored when masking feature was added.
716 // Hopefully Oslandia come back and fix this? Hint hint...
717
718 std::optional< QgsScopedRenderContextReferenceScaleOverride > referenceScaleOverride;
719 if ( mode == Qgis::TextLayoutMode::Labeling )
720 {
721 // label size has already been calculated using any symbology reference scale factor -- we need
722 // to temporarily remove the reference scale here or we'll be applying the scaling twice
723 referenceScaleOverride.emplace( QgsScopedRenderContextReferenceScaleOverride( context, -1.0 ) );
724 }
725
726 if ( metrics.isNullFontSize() )
727 return;
728
729 referenceScaleOverride.reset();
730
731 double xOffset = 0;
732 int fragmentIndex = 0;
733 for ( const QgsTextFragment &fragment : component.block )
734 {
735 if ( !fragment.isWhitespace() && !fragment.isImage() )
736 {
737 const QFont fragmentFont = metrics.fragmentFont( component.blockIndex, fragmentIndex );
738
739 const double fragmentYOffset = metrics.fragmentVerticalOffset( component.blockIndex, fragmentIndex, mode );
740 path.addText( xOffset, fragmentYOffset, fragmentFont, fragment.text() );
741 }
742
743 xOffset += metrics.fragmentHorizontalAdvance( component.blockIndex, fragmentIndex, mode ) * scaleFactor;
744 fragmentIndex++;
745 }
746
747 QColor bufferColor( Qt::gray );
748 bufferColor.setAlphaF( mask.opacity() );
749
750 QPen pen;
751 QBrush brush;
752 brush.setColor( bufferColor );
753 pen.setColor( bufferColor );
754 pen.setWidthF( penSize * scaleFactor );
755 pen.setJoinStyle( mask.joinStyle() );
756
757 QgsScopedQPainterState painterState( p );
758 context.setPainterFlagsUsingContext( p );
759
760 // scale for any print output or image saving @ specific dpi
761 p->scale( component.dpiRatio, component.dpiRatio );
762 if ( mask.paintEffect() && mask.paintEffect()->enabled() )
763 {
764 QgsPainterSwapper swapper( context, p );
765 {
766 QgsEffectPainter effectPainter( context, mask.paintEffect() );
767 if ( scaleFactor != 1.0 )
768 context.painter()->scale( 1 / scaleFactor, 1 / scaleFactor );
769 context.painter()->setPen( pen );
770 context.painter()->setBrush( brush );
771 context.painter()->drawPath( path );
772 if ( scaleFactor != 1.0 )
773 context.painter()->scale( scaleFactor, scaleFactor );
774 }
775 }
776 else
777 {
778 if ( scaleFactor != 1.0 )
779 p->scale( 1 / scaleFactor, 1 / scaleFactor );
780 p->setPen( pen );
781 p->setBrush( brush );
782 p->drawPath( path );
783 if ( scaleFactor != 1.0 )
784 p->scale( scaleFactor, scaleFactor );
785
786 }
787}
788
789double QgsTextRenderer::textWidth( const QgsRenderContext &context, const QgsTextFormat &format, const QStringList &textLines, QFontMetricsF * )
790{
791 const QgsTextDocument doc = QgsTextDocument::fromTextAndFormat( textLines, format );
792 if ( doc.size() == 0 )
793 return 0;
794
795 return textWidth( context, format, doc );
796}
797
798double QgsTextRenderer::textWidth( const QgsRenderContext &context, const QgsTextFormat &format, const QgsTextDocument &document )
799{
800 //calculate max width of text lines
801 const double scaleFactor = calculateScaleFactorForFormat( context, format );
802
803 const QgsTextDocumentMetrics metrics = QgsTextDocumentMetrics::calculateMetrics( document, format, context, scaleFactor );
804
805 // width doesn't change depending on layout mode, we can use anything here
806 return metrics.documentSize( Qgis::TextLayoutMode::Point, format.orientation() ).width();
807}
808
809double QgsTextRenderer::textHeight( const QgsRenderContext &context, const QgsTextFormat &format, const QStringList &textLines, Qgis::TextLayoutMode mode, QFontMetricsF *, Qgis::TextRendererFlags flags, double maxLineWidth )
810{
811 QStringList lines;
812 for ( const QString &line : textLines )
813 {
814 if ( flags & Qgis::TextRendererFlag::WrapLines && maxLineWidth > 0 && textRequiresWrapping( context, line, maxLineWidth, format ) )
815 {
816 lines.append( wrappedText( context, line, maxLineWidth, format ) );
817 }
818 else
819 {
820 lines.append( line );
821 }
822 }
823
824 const QgsTextDocument doc = QgsTextDocument::fromTextAndFormat( lines, format );
825 return textHeight( context, format, doc, mode );
826}
827
828double QgsTextRenderer::textHeight( const QgsRenderContext &context, const QgsTextFormat &format, QChar character, bool includeEffects )
829{
830 const double scaleFactor = calculateScaleFactorForFormat( context, format );
831
832 bool isNullSize = false;
833 const QFont baseFont = format.scaledFont( context, scaleFactor, &isNullSize );
834 if ( isNullSize )
835 return 0;
836
837 const QFontMetrics fm( baseFont );
838 const double height = ( character.isNull() ? fm.height() : fm.boundingRect( character ).height() ) / scaleFactor;
839
840 if ( !includeEffects )
841 return height;
842
843 double maxExtension = 0;
844 const double fontSize = context.convertToPainterUnits( format.size(), format.sizeUnit(), format.sizeMapUnitScale() );
845 if ( format.buffer().enabled() )
846 {
847 maxExtension += format.buffer().sizeUnit() == Qgis::RenderUnit::Percentage
848 ? fontSize * format.buffer().size() / 100
849 : context.convertToPainterUnits( format.buffer().size(), format.buffer().sizeUnit(), format.buffer().sizeMapUnitScale() );
850 }
851 if ( format.shadow().enabled() )
852 {
853 maxExtension += ( format.shadow().offsetUnit() == Qgis::RenderUnit::Percentage
854 ? fontSize * format.shadow().offsetDistance() / 100
855 : context.convertToPainterUnits( format.shadow().offsetDistance(), format.shadow().offsetUnit(), format.shadow().offsetMapUnitScale() )
856 )
858 ? fontSize * format.shadow().blurRadius() / 100
859 : context.convertToPainterUnits( format.shadow().blurRadius(), format.shadow().blurRadiusUnit(), format.shadow().blurRadiusMapUnitScale() )
860 );
861 }
862 if ( format.background().enabled() )
863 {
864 maxExtension += context.convertToPainterUnits( std::fabs( format.background().offset().y() ), format.background().offsetUnit(), format.background().offsetMapUnitScale() )
866 if ( format.background().sizeType() == QgsTextBackgroundSettings::SizeBuffer && format.background().size().height() > 0 )
867 {
868 maxExtension += context.convertToPainterUnits( format.background().size().height(), format.background().sizeUnit(), format.background().sizeMapUnitScale() );
869 }
870 }
871
872 return height + maxExtension;
873}
874
875bool QgsTextRenderer::textRequiresWrapping( const QgsRenderContext &context, const QString &text, double width, const QgsTextFormat &format )
876{
877 if ( qgsDoubleNear( width, 0.0 ) )
878 return false;
879
880 const QStringList multiLineSplit = text.split( '\n' );
881 const double currentTextWidth = QgsTextRenderer::textWidth( context, format, multiLineSplit );
882 return currentTextWidth > width;
883}
884
885QStringList QgsTextRenderer::wrappedText( const QgsRenderContext &context, const QString &text, double width, const QgsTextFormat &format )
886{
887 const QStringList lines = text.split( '\n' );
888 QStringList outLines;
889 for ( const QString &line : lines )
890 {
891 if ( textRequiresWrapping( context, line, width, format ) )
892 {
893 //first step is to identify words which must be on their own line (too long to fit)
894 const QStringList words = line.split( ' ' );
895 QStringList linesToProcess;
896 QString wordsInCurrentLine;
897 for ( const QString &word : words )
898 {
899 if ( textRequiresWrapping( context, word, width, format ) )
900 {
901 //too long to fit
902 if ( !wordsInCurrentLine.isEmpty() )
903 linesToProcess << wordsInCurrentLine;
904 wordsInCurrentLine.clear();
905 linesToProcess << word;
906 }
907 else
908 {
909 if ( !wordsInCurrentLine.isEmpty() )
910 wordsInCurrentLine.append( ' ' );
911 wordsInCurrentLine.append( word );
912 }
913 }
914 if ( !wordsInCurrentLine.isEmpty() )
915 linesToProcess << wordsInCurrentLine;
916
917 for ( const QString &line : std::as_const( linesToProcess ) )
918 {
919 QString remainingText = line;
920 int lastPos = remainingText.lastIndexOf( ' ' );
921 while ( lastPos > -1 )
922 {
923 //check if remaining text is short enough to go in one line
924 if ( !textRequiresWrapping( context, remainingText, width, format ) )
925 {
926 break;
927 }
928
929 if ( !textRequiresWrapping( context, remainingText.left( lastPos ), width, format ) )
930 {
931 outLines << remainingText.left( lastPos );
932 remainingText = remainingText.mid( lastPos + 1 );
933 lastPos = 0;
934 }
935 lastPos = remainingText.lastIndexOf( ' ', lastPos - 1 );
936 }
937 outLines << remainingText;
938 }
939 }
940 else
941 {
942 outLines << line;
943 }
944 }
945
946 return outLines;
947}
948
949double QgsTextRenderer::textHeight( const QgsRenderContext &context, const QgsTextFormat &format, const QgsTextDocument &doc, Qgis::TextLayoutMode mode )
950{
951 QgsTextDocument document = doc;
952 document.applyCapitalization( format.capitalization() );
953
954 //calculate max height of text lines
955 const double scaleFactor = calculateScaleFactorForFormat( context, format );
956
957 const QgsTextDocumentMetrics metrics = QgsTextDocumentMetrics::calculateMetrics( document, format, context, scaleFactor );
958 if ( metrics.isNullFontSize() )
959 return 0;
960
961 return metrics.documentSize( mode, format.orientation() ).height();
962}
963
964void QgsTextRenderer::drawBackground( QgsRenderContext &context, QgsTextRenderer::Component component, const QgsTextFormat &format, const QgsTextDocumentMetrics &metrics, Qgis::TextLayoutMode mode )
965{
966 QgsTextBackgroundSettings background = format.background();
967
968 QPainter *prevP = context.painter();
969 QPainter *p = context.painter();
970 std::unique_ptr< QgsPaintEffect > tmpEffect;
971 if ( background.paintEffect() && background.paintEffect()->enabled() )
972 {
973 tmpEffect.reset( background.paintEffect()->clone() );
974 tmpEffect->begin( context );
975 p = context.painter();
976 }
977
978 //QgsDebugMsgLevel( QStringLiteral( "Background label rotation: %1" ).arg( component.rotation() ), 4 );
979
980 // shared calculations between shapes and SVG
981
982 // configure angles, set component rotation and rotationOffset
983 const double originAdjustRotationRadians = -component.rotation;
985 {
986 component.rotation = -( component.rotation * 180 / M_PI ); // RotationSync
987 component.rotationOffset =
988 background.rotationType() == QgsTextBackgroundSettings::RotationOffset ? background.rotation() : 0.0;
989 }
990 else // RotationFixed
991 {
992 component.rotation = 0.0; // don't use label's rotation
993 component.rotationOffset = background.rotation();
994 }
995
996 const double scaleFactor = calculateScaleFactorForFormat( context, format );
997
998 if ( mode != Qgis::TextLayoutMode::Labeling )
999 {
1000 // need to calculate size of text
1001 const QSizeF documentSize = metrics.documentSize( mode, format.orientation() );
1002 double width = documentSize.width();
1003 double height = documentSize.height();
1004
1005 switch ( mode )
1006 {
1010 switch ( component.hAlign )
1011 {
1014 component.center = QPointF( component.origin.x() + width / 2.0,
1015 component.origin.y() + height / 2.0 );
1016 break;
1017
1019 component.center = QPointF( component.origin.x() + component.size.width() / 2.0,
1020 component.origin.y() + height / 2.0 );
1021 break;
1022
1024 component.center = QPointF( component.origin.x() + component.size.width() - width / 2.0,
1025 component.origin.y() + height / 2.0 );
1026 break;
1027 }
1028 break;
1029
1031 {
1032 bool isNullSize = false;
1033 QFontMetricsF fm( format.scaledFont( context, scaleFactor, &isNullSize ) );
1034 double originAdjust = isNullSize ? 0 : ( fm.ascent() / scaleFactor / 2.0 - fm.leading() / scaleFactor / 2.0 );
1035 switch ( component.hAlign )
1036 {
1039 component.center = QPointF( component.origin.x() + width / 2.0,
1040 component.origin.y() - height / 2.0 + originAdjust );
1041 break;
1042
1044 component.center = QPointF( component.origin.x(),
1045 component.origin.y() - height / 2.0 + originAdjust );
1046 break;
1047
1049 component.center = QPointF( component.origin.x() - width / 2.0,
1050 component.origin.y() - height / 2.0 + originAdjust );
1051 break;
1052 }
1053
1054 // apply rotation to center point
1055 if ( !qgsDoubleNear( originAdjustRotationRadians, 0 ) )
1056 {
1057 const double dx = component.center.x() - component.origin.x();
1058 const double dy = component.center.y() - component.origin.y();
1059 component.center.setX( component.origin.x() + ( std::cos( originAdjustRotationRadians ) * dx - std::sin( originAdjustRotationRadians ) * dy ) );
1060 component.center.setY( component.origin.y() + ( std::sin( originAdjustRotationRadians ) * dx + std::cos( originAdjustRotationRadians ) * dy ) );
1061 }
1062 break;
1063 }
1064
1066 break;
1067 }
1068
1070 component.size = QSizeF( width, height );
1071 }
1072
1073 // TODO: the following label-buffered generated shapes and SVG symbols should be moved into marker symbology classes
1074
1075 switch ( background.type() )
1076 {
1079 {
1080 // all calculations done in shapeSizeUnits, which are then passed to symbology class for painting
1081
1082 if ( background.type() == QgsTextBackgroundSettings::ShapeSVG && background.svgFile().isEmpty() )
1083 return;
1084
1085 if ( background.type() == QgsTextBackgroundSettings::ShapeMarkerSymbol && !background.markerSymbol() )
1086 return;
1087
1088 double sizeOut = 0.0;
1089 {
1090 QgsScopedRenderContextReferenceScaleOverride referenceScaleOverride( context, -1 );
1091
1092 // only one size used for SVG/marker symbol sizing/scaling (no use of shapeSize.y() or Y field in gui)
1093 if ( background.sizeType() == QgsTextBackgroundSettings::SizeFixed )
1094 {
1095 sizeOut = context.convertToPainterUnits( background.size().width(), background.sizeUnit(), background.sizeMapUnitScale() );
1096 }
1097 else if ( background.sizeType() == QgsTextBackgroundSettings::SizeBuffer )
1098 {
1099 sizeOut = std::max( component.size.width(), component.size.height() );
1100 double bufferSize = context.convertToPainterUnits( background.size().width(), background.sizeUnit(), background.sizeMapUnitScale() );
1101
1102 // add buffer
1103 sizeOut += bufferSize * 2;
1104 }
1105 }
1106
1107 // don't bother rendering symbols smaller than 1x1 pixels in size
1108 // TODO: add option to not show any svgs under/over a certain size
1109 if ( sizeOut < 1.0 )
1110 return;
1111
1112 std::unique_ptr< QgsMarkerSymbol > renderedSymbol;
1113 if ( background.type() == QgsTextBackgroundSettings::ShapeSVG )
1114 {
1115 QVariantMap map; // for SVG symbology marker
1116 map[QStringLiteral( "name" )] = background.svgFile().trimmed();
1117 map[QStringLiteral( "size" )] = QString::number( sizeOut );
1118 map[QStringLiteral( "size_unit" )] = QgsUnitTypes::encodeUnit( Qgis::RenderUnit::Pixels );
1119 map[QStringLiteral( "angle" )] = QString::number( 0.0 ); // angle is handled by this local painter
1120
1121 // offset is handled by this local painter
1122 // TODO: see why the marker renderer doesn't seem to translate offset *after* applying rotation
1123 //map["offset"] = QgsSymbolLayerUtils::encodePoint( tmpLyr.shapeOffset );
1124 //map["offset_unit"] = QgsUnitTypes::encodeUnit(
1125 // tmpLyr.shapeOffsetUnits == QgsPalLayerSettings::MapUnits ? QgsUnitTypes::MapUnit : QgsUnitTypes::MM );
1126
1127 map[QStringLiteral( "fill" )] = background.fillColor().name();
1128 map[QStringLiteral( "outline" )] = background.strokeColor().name();
1129 map[QStringLiteral( "outline-width" )] = QString::number( background.strokeWidth() );
1130 map[QStringLiteral( "outline_width_unit" )] = QgsUnitTypes::encodeUnit( background.strokeWidthUnit() );
1131
1133 {
1134 QgsTextShadowSettings shadow = format.shadow();
1135 // configure SVG shadow specs
1136 QVariantMap shdwmap( map );
1137 shdwmap[QStringLiteral( "fill" )] = shadow.color().name();
1138 shdwmap[QStringLiteral( "outline" )] = shadow.color().name();
1139 shdwmap[QStringLiteral( "size" )] = QString::number( sizeOut );
1140
1141 // store SVG's drawing in QPicture for drop shadow call
1142 QPicture svgPict;
1143 QPainter svgp;
1144 svgp.begin( &svgPict );
1145
1146 // draw shadow symbol
1147
1148 // clone current render context map unit/mm conversion factors, but not
1149 // other map canvas parameters, then substitute this painter for use in symbology painting
1150 // NOTE: this is because the shadow needs to be scaled correctly for output to map canvas,
1151 // but will be created relative to the SVG's computed size, not the current map canvas
1152 QgsRenderContext shdwContext;
1153 shdwContext.setMapToPixel( context.mapToPixel() );
1154 shdwContext.setScaleFactor( context.scaleFactor() );
1155 shdwContext.setPainter( &svgp );
1156
1157 std::unique_ptr< QgsSymbolLayer > symShdwL( QgsSvgMarkerSymbolLayer::create( shdwmap ) );
1158 QgsSvgMarkerSymbolLayer *svgShdwM = static_cast<QgsSvgMarkerSymbolLayer *>( symShdwL.get() );
1159 QgsSymbolRenderContext svgShdwContext( shdwContext, Qgis::RenderUnit::Unknown, background.opacity() );
1160
1161 svgShdwM->renderPoint( QPointF( sizeOut / 2, -sizeOut / 2 ), svgShdwContext );
1162 svgp.end();
1163
1164 component.picture = svgPict;
1165 // TODO: when SVG symbol's stroke width/units is fixed in QgsSvgCache, adjust for it here
1166 component.pictureBuffer = 0.0;
1167
1168 component.size = QSizeF( sizeOut, sizeOut );
1169 component.offset = QPointF( 0.0, 0.0 );
1170
1171 // rotate about origin center of SVG
1172 QgsScopedQPainterState painterState( p );
1173 context.setPainterFlagsUsingContext( p );
1174
1175 p->translate( component.center.x(), component.center.y() );
1176 p->rotate( component.rotation );
1177 double xoff = context.convertToPainterUnits( background.offset().x(), background.offsetUnit(), background.offsetMapUnitScale() );
1178 double yoff = context.convertToPainterUnits( background.offset().y(), background.offsetUnit(), background.offsetMapUnitScale() );
1179 p->translate( QPointF( xoff, yoff ) );
1180 p->rotate( component.rotationOffset );
1181 p->translate( -sizeOut / 2, sizeOut / 2 );
1182
1183 drawShadow( context, component, format );
1184 }
1185 renderedSymbol.reset( );
1186
1188 renderedSymbol.reset( new QgsMarkerSymbol( QgsSymbolLayerList() << symL ) );
1189 }
1190 else
1191 {
1192 renderedSymbol.reset( background.markerSymbol()->clone() );
1193 renderedSymbol->setSize( sizeOut );
1194 renderedSymbol->setSizeUnit( Qgis::RenderUnit::Pixels );
1195 }
1196
1197 renderedSymbol->setOpacity( renderedSymbol->opacity() * background.opacity() );
1198
1199 // draw the actual symbol
1200 QgsScopedQPainterState painterState( p );
1201 context.setPainterFlagsUsingContext( p );
1202
1203 if ( context.useAdvancedEffects() )
1204 {
1205 p->setCompositionMode( background.blendMode() );
1206 }
1207 p->translate( component.center.x(), component.center.y() );
1208 p->rotate( component.rotation );
1209 double xoff = context.convertToPainterUnits( background.offset().x(), background.offsetUnit(), background.offsetMapUnitScale() );
1210 double yoff = context.convertToPainterUnits( background.offset().y(), background.offsetUnit(), background.offsetMapUnitScale() );
1211 p->translate( QPointF( xoff, yoff ) );
1212 p->rotate( component.rotationOffset );
1213
1214 const QgsFeature f = context.expressionContext().feature();
1215 renderedSymbol->startRender( context, context.expressionContext().fields() );
1216 renderedSymbol->renderPoint( QPointF( 0, 0 ), &f, context );
1217 renderedSymbol->stopRender( context );
1218 p->setCompositionMode( QPainter::CompositionMode_SourceOver ); // just to be sure
1219
1220 break;
1221 }
1222
1227 {
1228 double w = component.size.width();
1229 double h = component.size.height();
1230
1231 if ( background.sizeType() == QgsTextBackgroundSettings::SizeFixed )
1232 {
1233 w = context.convertToPainterUnits( background.size().width(), background.sizeUnit(),
1234 background.sizeMapUnitScale() );
1235 h = context.convertToPainterUnits( background.size().height(), background.sizeUnit(),
1236 background.sizeMapUnitScale() );
1237 }
1238 else if ( background.sizeType() == QgsTextBackgroundSettings::SizeBuffer )
1239 {
1240 if ( background.type() == QgsTextBackgroundSettings::ShapeSquare )
1241 {
1242 if ( w > h )
1243 h = w;
1244 else if ( h > w )
1245 w = h;
1246 }
1247 else if ( background.type() == QgsTextBackgroundSettings::ShapeCircle )
1248 {
1249 // start with label bound by circle
1250 h = std::sqrt( std::pow( w, 2 ) + std::pow( h, 2 ) );
1251 w = h;
1252 }
1253 else if ( background.type() == QgsTextBackgroundSettings::ShapeEllipse )
1254 {
1255 // start with label bound by ellipse
1256 h = h * M_SQRT1_2 * 2;
1257 w = w * M_SQRT1_2 * 2;
1258 }
1259
1260 double bufferWidth = context.convertToPainterUnits( background.size().width(), background.sizeUnit(),
1261 background.sizeMapUnitScale() );
1262 double bufferHeight = context.convertToPainterUnits( background.size().height(), background.sizeUnit(),
1263 background.sizeMapUnitScale() );
1264
1265 w += bufferWidth * 2;
1266 h += bufferHeight * 2;
1267 }
1268
1269 // offsets match those of symbology: -x = left, -y = up
1270 QRectF rect( -w / 2.0, - h / 2.0, w, h );
1271
1272 if ( rect.isNull() )
1273 return;
1274
1275 QgsScopedQPainterState painterState( p );
1276 context.setPainterFlagsUsingContext( p );
1277
1278 p->translate( QPointF( component.center.x(), component.center.y() ) );
1279 p->rotate( component.rotation );
1280 double xoff = context.convertToPainterUnits( background.offset().x(), background.offsetUnit(), background.offsetMapUnitScale() );
1281 double yoff = context.convertToPainterUnits( background.offset().y(), background.offsetUnit(), background.offsetMapUnitScale() );
1282 p->translate( QPointF( xoff, yoff ) );
1283 p->rotate( component.rotationOffset );
1284
1285 QPainterPath path;
1286
1287 // Paths with curves must be enlarged before conversion to QPolygonF, or
1288 // the curves are approximated too much and appear jaggy
1289 QTransform t = QTransform::fromScale( 10, 10 );
1290 // inverse transform used to scale created polygons back to expected size
1291 QTransform ti = t.inverted();
1292
1294 || background.type() == QgsTextBackgroundSettings::ShapeSquare )
1295 {
1296 if ( background.radiiUnit() == Qgis::RenderUnit::Percentage )
1297 {
1298 path.addRoundedRect( rect, background.radii().width(), background.radii().height(), Qt::RelativeSize );
1299 }
1300 else
1301 {
1302 const double xRadius = context.convertToPainterUnits( background.radii().width(), background.radiiUnit(), background.radiiMapUnitScale() );
1303 const double yRadius = context.convertToPainterUnits( background.radii().height(), background.radiiUnit(), background.radiiMapUnitScale() );
1304 path.addRoundedRect( rect, xRadius, yRadius );
1305 }
1306 }
1307 else if ( background.type() == QgsTextBackgroundSettings::ShapeEllipse
1308 || background.type() == QgsTextBackgroundSettings::ShapeCircle )
1309 {
1310 path.addEllipse( rect );
1311 }
1312 QPolygonF tempPolygon = path.toFillPolygon( t );
1313 QPolygonF polygon = ti.map( tempPolygon );
1314 QPicture shapePict;
1315 QPainter *oldp = context.painter();
1316 QPainter shapep;
1317
1318 shapep.begin( &shapePict );
1319 context.setPainter( &shapep );
1320
1321 std::unique_ptr< QgsFillSymbol > renderedSymbol;
1322 renderedSymbol.reset( background.fillSymbol()->clone() );
1323 renderedSymbol->setOpacity( renderedSymbol->opacity() * background.opacity() );
1324
1325 const QgsFeature f = context.expressionContext().feature();
1326 renderedSymbol->startRender( context, context.expressionContext().fields() );
1327 renderedSymbol->renderPolygon( polygon, nullptr, &f, context );
1328 renderedSymbol->stopRender( context );
1329
1330 shapep.end();
1331 context.setPainter( oldp );
1332
1334 {
1335 component.picture = shapePict;
1336 component.pictureBuffer = QgsSymbolLayerUtils::estimateMaxSymbolBleed( renderedSymbol.get(), context ) * 2;
1337
1338 component.size = rect.size();
1339 component.offset = QPointF( rect.width() / 2, -rect.height() / 2 );
1340 drawShadow( context, component, format );
1341 }
1342
1343 if ( context.useAdvancedEffects() )
1344 {
1345 p->setCompositionMode( background.blendMode() );
1346 }
1347
1348 // scale for any print output or image saving @ specific dpi
1349 p->scale( component.dpiRatio, component.dpiRatio );
1351 p->drawPicture( 0, 0, shapePict );
1352 p->setCompositionMode( QPainter::CompositionMode_SourceOver ); // just to be sure
1353 break;
1354 }
1355 }
1356
1357 if ( tmpEffect )
1358 {
1359 tmpEffect->end( context );
1360 context.setPainter( prevP );
1361 }
1362}
1363
1364void QgsTextRenderer::drawShadow( QgsRenderContext &context, const QgsTextRenderer::Component &component, const QgsTextFormat &format )
1365{
1366 QgsTextShadowSettings shadow = format.shadow();
1367
1368 QPainter *p = context.painter();
1369 const double componentWidth = component.size.width();
1370 const double componentHeight = component.size.height();
1371 const double xOffset = component.offset.x();
1372 const double yOffset = component.offset.y();
1373 double pictbuffer = component.pictureBuffer;
1374
1375 // generate pixmap representation of label component drawing
1376 bool mapUnits = shadow.blurRadiusUnit() == Qgis::RenderUnit::MapUnits;
1377
1378 const double fontSize = context.convertToPainterUnits( format.size(), format.sizeUnit(), format.sizeMapUnitScale() );
1379 double radius = shadow.blurRadiusUnit() == Qgis::RenderUnit::Percentage
1380 ? fontSize * shadow.blurRadius() / 100
1381 : context.convertToPainterUnits( shadow.blurRadius(), shadow.blurRadiusUnit(), shadow.blurRadiusMapUnitScale() );
1382 radius /= ( mapUnits ? context.scaleFactor() / component.dpiRatio : 1 );
1383 radius = static_cast< int >( radius + 0.5 ); //NOLINT
1384
1385 // TODO: add labeling gui option to adjust blurBufferClippingScale to minimize pixels, or
1386 // to ensure shadow isn't clipped too tight. (Or, find a better method of buffering)
1387 double blurBufferClippingScale = 3.75;
1388 int blurbuffer = ( radius > 17 ? 16 : radius ) * blurBufferClippingScale;
1389
1390 QImage blurImg( componentWidth + ( pictbuffer * 2.0 ) + ( blurbuffer * 2.0 ),
1391 componentHeight + ( pictbuffer * 2.0 ) + ( blurbuffer * 2.0 ),
1392 QImage::Format_ARGB32_Premultiplied );
1393
1394 // TODO: add labeling gui option to not show any shadows under/over a certain size
1395 // keep very small QImages from causing paint device issues, i.e. must be at least > 1
1396 int minBlurImgSize = 1;
1397 // max limitation on QgsSvgCache is 10,000 for screen, which will probably be reasonable for future caching here, too
1398 // 4 x QgsSvgCache limit for output to print/image at higher dpi
1399 // TODO: should it be higher, scale with dpi, or have no limit? Needs testing with very large labels rendered at high dpi output
1400 int maxBlurImgSize = 40000;
1401 if ( blurImg.isNull()
1402 || ( blurImg.width() < minBlurImgSize || blurImg.height() < minBlurImgSize )
1403 || ( blurImg.width() > maxBlurImgSize || blurImg.height() > maxBlurImgSize ) )
1404 return;
1405
1406 blurImg.fill( QColor( Qt::transparent ).rgba() );
1407 QPainter pictp;
1408 if ( !pictp.begin( &blurImg ) )
1409 return;
1410 pictp.setRenderHints( QPainter::Antialiasing | QPainter::SmoothPixmapTransform );
1411 QPointF imgOffset( blurbuffer + pictbuffer + xOffset,
1412 blurbuffer + pictbuffer + componentHeight + yOffset );
1413
1414 pictp.drawPicture( imgOffset,
1415 component.picture );
1416
1417 // overlay shadow color
1418 pictp.setCompositionMode( QPainter::CompositionMode_SourceIn );
1419 pictp.fillRect( blurImg.rect(), shadow.color() );
1420 pictp.end();
1421
1422 // blur the QImage in-place
1423 if ( shadow.blurRadius() > 0.0 && radius > 0 )
1424 {
1425 QgsSymbolLayerUtils::blurImageInPlace( blurImg, blurImg.rect(), radius, shadow.blurAlphaOnly() );
1426 }
1427
1428#if 0
1429 // debug rect for QImage shadow registration and clipping visualization
1430 QPainter picti;
1431 picti.begin( &blurImg );
1432 picti.setBrush( Qt::Dense7Pattern );
1433 QPen imgPen( QColor( 0, 0, 255, 255 ) );
1434 imgPen.setWidth( 1 );
1435 picti.setPen( imgPen );
1436 picti.setOpacity( 0.1 );
1437 picti.drawRect( 0, 0, blurImg.width(), blurImg.height() );
1438 picti.end();
1439#endif
1440
1441 const double offsetDist = shadow.offsetUnit() == Qgis::RenderUnit::Percentage
1442 ? fontSize * shadow.offsetDistance() / 100
1443 : context.convertToPainterUnits( shadow.offsetDistance(), shadow.offsetUnit(), shadow.offsetMapUnitScale() );
1444 double angleRad = shadow.offsetAngle() * M_PI / 180; // to radians
1445 if ( shadow.offsetGlobal() )
1446 {
1447 // TODO: check for differences in rotation origin and cw/ccw direction,
1448 // when this shadow function is used for something other than labels
1449
1450 // it's 0-->cw-->360 for labels
1451 //QgsDebugMsgLevel( QStringLiteral( "Shadow aggregated label rotation (degrees): %1" ).arg( component.rotation() + component.rotationOffset() ), 4 );
1452 angleRad -= ( component.rotation * M_PI / 180 + component.rotationOffset * M_PI / 180 );
1453 }
1454
1455 QPointF transPt( -offsetDist * std::cos( angleRad + M_PI_2 ),
1456 -offsetDist * std::sin( angleRad + M_PI_2 ) );
1457
1458 p->save();
1459 context.setPainterFlagsUsingContext( p );
1460 // this was historically ALWAYS set for text renderer. We may want to consider getting it to respect the
1461 // corresponding flag in the render context instead...
1462 p->setRenderHint( QPainter::SmoothPixmapTransform );
1463 if ( context.useAdvancedEffects() )
1464 {
1465 p->setCompositionMode( shadow.blendMode() );
1466 }
1467 p->setOpacity( shadow.opacity() );
1468
1469 double scale = shadow.scale() / 100.0;
1470 // TODO: scale from center/center, left/center or left/top, instead of default left/bottom?
1471 p->scale( scale, scale );
1472 if ( component.useOrigin )
1473 {
1474 p->translate( component.origin.x(), component.origin.y() );
1475 }
1476 p->translate( transPt );
1477 p->translate( -imgOffset.x(),
1478 -imgOffset.y() );
1479 p->drawImage( 0, 0, blurImg );
1480 p->restore();
1481
1482 // debug rects
1483#if 0
1484 // draw debug rect for QImage painting registration
1485 p->save();
1486 p->setBrush( Qt::NoBrush );
1487 QPen imgPen( QColor( 255, 0, 0, 10 ) );
1488 imgPen.setWidth( 2 );
1489 imgPen.setStyle( Qt::DashLine );
1490 p->setPen( imgPen );
1491 p->scale( scale, scale );
1492 if ( component.useOrigin() )
1493 {
1494 p->translate( component.origin().x(), component.origin().y() );
1495 }
1496 p->translate( transPt );
1497 p->translate( -imgOffset.x(),
1498 -imgOffset.y() );
1499 p->drawRect( 0, 0, blurImg.width(), blurImg.height() );
1500 p->restore();
1501
1502 // draw debug rect for passed in component dimensions
1503 p->save();
1504 p->setBrush( Qt::NoBrush );
1505 QPen componentRectPen( QColor( 0, 255, 0, 70 ) );
1506 componentRectPen.setWidth( 1 );
1507 if ( component.useOrigin() )
1508 {
1509 p->translate( component.origin().x(), component.origin().y() );
1510 }
1511 p->setPen( componentRectPen );
1512 p->drawRect( QRect( -xOffset, -componentHeight - yOffset, componentWidth, componentHeight ) );
1513 p->restore();
1514#endif
1515}
1516
1517
1518void QgsTextRenderer::drawTextInternal( Qgis::TextComponents components,
1519 QgsRenderContext &context,
1520 const QgsTextFormat &format,
1521 const Component &component,
1522 const QgsTextDocument &document,
1523 const QgsTextDocumentMetrics &metrics,
1525{
1526 if ( !context.painter() )
1527 {
1528 return;
1529 }
1530
1531 const double fontScale = calculateScaleFactorForFormat( context, format );
1532
1533 std::optional< QgsScopedRenderContextReferenceScaleOverride > referenceScaleOverride;
1534 if ( mode == Qgis::TextLayoutMode::Labeling )
1535 {
1536 // label size has already been calculated using any symbology reference scale factor -- we need
1537 // to temporarily remove the reference scale here or we'll be applying the scaling twice
1538 referenceScaleOverride.emplace( QgsScopedRenderContextReferenceScaleOverride( context, -1.0 ) );
1539 }
1540
1541 if ( metrics.isNullFontSize() )
1542 return;
1543
1544 referenceScaleOverride.reset();
1545
1546 double rotation = 0;
1547 const Qgis::TextOrientation orientation = calculateRotationAndOrientationForComponent( format, component, rotation );
1548 switch ( orientation )
1549 {
1551 {
1552 drawTextInternalHorizontal( context, format, components, mode, component, document, metrics, fontScale, alignment, vAlignment, rotation );
1553 break;
1554 }
1555
1558 {
1559 // TODO: vertical text renderer currently doesn't handle one-pass buffer + text drawing
1560 if ( components & Qgis::TextComponent::Buffer )
1561 drawTextInternalVertical( context, format, Qgis::TextComponent::Buffer, mode, component, document, metrics, fontScale, alignment, vAlignment, rotation );
1562 if ( components & Qgis::TextComponent::Text )
1563 drawTextInternalVertical( context, format, Qgis::TextComponent::Text, mode, component, document, metrics, fontScale, alignment, vAlignment, rotation );
1564 break;
1565 }
1566 }
1567}
1568
1569Qgis::TextOrientation QgsTextRenderer::calculateRotationAndOrientationForComponent( const QgsTextFormat &format, const QgsTextRenderer::Component &component, double &rotation )
1570{
1571 rotation = -component.rotation * 180 / M_PI;
1572
1573 switch ( format.orientation() )
1574 {
1576 {
1577 // Between 45 to 135 and 235 to 315 degrees, rely on vertical orientation
1578 if ( rotation >= -315 && rotation < -90 )
1579 {
1580 rotation -= 90;
1582 }
1583 else if ( rotation >= -90 && rotation < -45 )
1584 {
1585 rotation += 90;
1587 }
1588
1590 }
1591
1594 return format.orientation();
1595 }
1597}
1598
1599void QgsTextRenderer::calculateExtraSpacingForLineJustification( const double spaceToDistribute, const QgsTextBlock &block, double &extraWordSpace, double &extraLetterSpace )
1600{
1601 const QString blockText = block.toPlainText();
1602 QTextBoundaryFinder finder( QTextBoundaryFinder::Word, blockText );
1603 finder.toStart();
1604 int wordBoundaries = 0;
1605 while ( finder.toNextBoundary() != -1 )
1606 {
1607 if ( finder.boundaryReasons() & QTextBoundaryFinder::StartOfItem )
1608 wordBoundaries++;
1609 }
1610
1611 if ( wordBoundaries > 0 )
1612 {
1613 // word boundaries found => justify by padding word spacing
1614 extraWordSpace = spaceToDistribute / wordBoundaries;
1615 }
1616 else
1617 {
1618 // no word boundaries found => justify by letter spacing
1619 QTextBoundaryFinder finder( QTextBoundaryFinder::Grapheme, blockText );
1620 finder.toStart();
1621
1622 int graphemeBoundaries = 0;
1623 while ( finder.toNextBoundary() != -1 )
1624 {
1625 if ( finder.boundaryReasons() & QTextBoundaryFinder::StartOfItem )
1626 graphemeBoundaries++;
1627 }
1628
1629 if ( graphemeBoundaries > 0 )
1630 {
1631 extraLetterSpace = spaceToDistribute / graphemeBoundaries;
1632 }
1633 }
1634}
1635
1636void QgsTextRenderer::applyExtraSpacingForLineJustification( QFont &font, double extraWordSpace, double extraLetterSpace )
1637{
1638 const double prevWordSpace = font.wordSpacing();
1639 font.setWordSpacing( prevWordSpace + extraWordSpace );
1640 const double prevLetterSpace = font.letterSpacing();
1641 font.setLetterSpacing( QFont::AbsoluteSpacing, prevLetterSpace + extraLetterSpace );
1642}
1643
1644
1645void QgsTextRenderer::renderBlockHorizontal( const QgsTextBlock &block, int blockIndex,
1646 const QgsTextDocumentMetrics &metrics, QgsRenderContext &context,
1647 const QgsTextFormat &format,
1648 QPainter *painter, bool forceRenderAsPaths,
1649 double fontScale, double extraWordSpace, double extraLetterSpace,
1650 Qgis::TextLayoutMode mode, DeferredRenderBlock *deferredRenderBlock )
1651{
1652 if ( !metrics.isNullFontSize() )
1653 {
1654 double xOffset = 0;
1655 int fragmentIndex = 0;
1656 for ( const QgsTextFragment &fragment : block )
1657 {
1658 // draw text, QPainterPath method
1659 if ( !fragment.isWhitespace() && !fragment.isImage() )
1660 {
1661 QFont fragmentFont = metrics.fragmentFont( blockIndex, fragmentIndex );
1662
1663 if ( !qgsDoubleNear( extraWordSpace, 0 ) || !qgsDoubleNear( extraLetterSpace, 0 ) )
1664 applyExtraSpacingForLineJustification( fragmentFont, extraWordSpace * fontScale, extraLetterSpace * fontScale );
1665
1666 const double yOffset = metrics.fragmentVerticalOffset( blockIndex, fragmentIndex, mode );
1667
1668 QColor textColor = fragment.characterFormat().textColor().isValid() ? fragment.characterFormat().textColor() : format.color();
1669 textColor.setAlphaF( fragment.characterFormat().textColor().isValid() ? textColor.alphaF() * format.opacity() : format.opacity() );
1670
1671 if ( deferredRenderBlock )
1672 {
1673 DeferredRenderFragment renderFragment;
1674 renderFragment.color = textColor;
1675 if ( forceRenderAsPaths )
1676 {
1677 renderFragment.path.setFillRule( Qt::WindingFill );
1678 renderFragment.path.addText( xOffset, yOffset, fragmentFont, fragment.text() );
1679 }
1680 renderFragment.font = fragmentFont;
1681 renderFragment.point = QPointF( xOffset, yOffset );
1682 renderFragment.text = fragment.text();
1683 deferredRenderBlock->fragments.append( renderFragment );
1684 }
1685 else if ( forceRenderAsPaths )
1686 {
1687 painter->setBrush( textColor );
1688 QPainterPath path;
1689 path.setFillRule( Qt::WindingFill );
1690 path.addText( xOffset, yOffset, fragmentFont, fragment.text() );
1691 painter->drawPath( path );
1692 }
1693 else
1694 {
1695 painter->setPen( textColor );
1696 painter->setFont( fragmentFont );
1697 painter->drawText( QPointF( xOffset, yOffset ), fragment.text() );
1698 }
1699 }
1700 else if ( fragment.isImage() )
1701 {
1702 bool fitsInCache = false;
1703 const double imageWidth = metrics.fragmentHorizontalAdvance( blockIndex, fragmentIndex, mode ) * fontScale;
1704 const double imageHeight = metrics.fragmentFixedHeight( blockIndex, fragmentIndex, mode ) * fontScale;
1705
1706 const QImage image = QgsApplication::imageCache()->pathAsImage( fragment.characterFormat().imagePath(),
1707 QSize( static_cast< int >( std::round( imageWidth ) ),
1708 static_cast< int >( std::round( imageHeight ) ) ),
1709 false,
1710 1, fitsInCache, context.flags() & Qgis::RenderContextFlag::RenderBlocking );
1711 const double imageBaseline = metrics.fragmentVerticalOffset( blockIndex, fragmentIndex, mode );
1712 const double yOffset = imageBaseline - image.height();
1713 if ( !image.isNull() )
1714 painter->drawImage( QPointF( xOffset, yOffset ), image );
1715 }
1716
1717 xOffset += metrics.fragmentHorizontalAdvance( blockIndex, fragmentIndex, mode ) * fontScale;
1718 fragmentIndex ++;
1719 }
1720 }
1721};
1722
1723bool QgsTextRenderer::usePathsToRender( const QgsRenderContext &context, const QgsTextFormat &format, const QgsTextDocument &document )
1724{
1725 switch ( context.textRenderFormat() )
1726 {
1728 return true;
1730 return false;
1732 {
1733 // Prefer not to use paths -- but certain conditions will require us to use them
1734 if ( format.buffer().enabled() )
1735 {
1736 // text buffer requires use of paths
1737 // TODO: this was the original cause of use switching from text to paths by default,
1738 // but that was way back in the 2.0 days and maybe the Qt issues have now been fixed?
1739 return true;
1740 }
1741
1742 // underline/overline/strikethrough looks different between path/non-path renders.
1743 // TODO: validate which is correct. For now, maintain default appearance from before this code
1744 // was introduced
1745 if ( format.font().underline()
1746 || format.font().overline()
1747 || format.font().strikeOut()
1748 || std::any_of( document.begin(), document.end(), []( const QgsTextBlock & block )
1749 {
1750 return std::any_of( block.begin(), block.end(), []( const QgsTextFragment & fragment )
1751 {
1752 return fragment.characterFormat().underline() == QgsTextCharacterFormat::BooleanValue::SetTrue
1753 || fragment.characterFormat().overline() == QgsTextCharacterFormat::BooleanValue::SetTrue
1754 || fragment.characterFormat().strikeOut() == QgsTextCharacterFormat::BooleanValue::SetTrue;
1755 } );
1756 } ) )
1757 return true;
1758
1759 return false;
1760 }
1761 }
1763}
1764
1765bool QgsTextRenderer::usePictureToRender( const QgsRenderContext &, const QgsTextFormat &, const QgsTextDocument &document )
1766{
1767 return std::any_of( document.begin(), document.end(), []( const QgsTextBlock & block )
1768 {
1769 return std::any_of( block.begin(), block.end(), []( const QgsTextFragment & fragment )
1770 {
1771 return fragment.isImage();
1772 } );
1773 } );
1774}
1775
1776void QgsTextRenderer::drawTextInternalHorizontal( QgsRenderContext &context, const QgsTextFormat &format, Qgis::TextComponents components, Qgis::TextLayoutMode mode, const Component &component, const QgsTextDocument &document, const QgsTextDocumentMetrics &metrics, double fontScale, const Qgis::TextHorizontalAlignment hAlignment,
1777 Qgis::TextVerticalAlignment vAlignment, double rotation )
1778{
1779 QPainter *maskPainter = context.maskPainter( context.currentMaskId() );
1780 const QStringList textLines = document.toPlainText();
1781
1782 const QSizeF documentSize = metrics.documentSize( mode, Qgis::TextOrientation::Horizontal );
1783
1784 double targetWidth = 0.0;
1785 switch ( mode )
1786 {
1789 targetWidth = documentSize.width();
1790 break;
1791
1795 targetWidth = component.size.width();
1796 break;
1797 }
1798
1799 double verticalAlignOffset = 0;
1800
1801 if ( mode == Qgis::TextLayoutMode::Rectangle )
1802 {
1803 const double overallHeight = documentSize.height();
1804 switch ( vAlignment )
1805 {
1807 verticalAlignOffset = metrics.blockVerticalMargin( - 1 );
1808 break;
1809
1811 verticalAlignOffset = ( component.size.height() - overallHeight ) * 0.5 + metrics.blockVerticalMargin( - 1 );
1812 break;
1813
1815 verticalAlignOffset = ( component.size.height() - overallHeight ) + metrics.blockVerticalMargin( - 1 );
1816 break;
1817 }
1818 }
1819 else if ( mode == Qgis::TextLayoutMode::Point )
1820 {
1821 verticalAlignOffset = - metrics.blockVerticalMargin( document.size() - 1 );
1822 }
1823
1824 // should we use text or paths for this render?
1825 const bool usePathsForText = usePathsToRender( context, format, document );
1826
1827 // TODO -- maybe we can avoid the nested vector? Need to confirm whether painter rotation & translation can be
1828 // done ONCE only, upfront
1829 std::unique_ptr< std::vector< DeferredRenderBlock > > deferredBlocks;
1830
1831 // Depending on format settings, we may need to render in multiple passes. Eg buffer than text, or shadow than text.
1832 // We try to avoid this if possible as it requires more work, and just do a single pass, rendering text directly as we go.
1833 // If we need to do multi-pass rendering then we'll calculate paths ONCE upfront and defer actually renderring these.
1834 const bool requiresMultiPassRendering = ( components & Qgis::TextComponent::Buffer && format.buffer().enabled() )
1836 if ( requiresMultiPassRendering )
1837 {
1838 deferredBlocks = std::make_unique< std::vector< DeferredRenderBlock > >();
1839 deferredBlocks->reserve( document.size() );
1840 }
1841
1842 int blockIndex = 0;
1843 for ( const QgsTextBlock &block : document )
1844 {
1845 Qgis::TextHorizontalAlignment blockAlignment = hAlignment;
1846 if ( block.blockFormat().hasHorizontalAlignmentSet() )
1847 blockAlignment = block.blockFormat().horizontalAlignment();
1848 const bool adjustForAlignment = blockAlignment != Qgis::TextHorizontalAlignment::Left &&
1850 || textLines.size() > 1 );
1851
1852 const bool isFinalLineInParagraph = ( blockIndex == document.size() - 1 )
1853 || document.at( blockIndex + 1 ).toPlainText().trimmed().isEmpty();
1854
1855 const double blockHeight = metrics.blockHeight( blockIndex );
1856
1857 DeferredRenderBlock *deferredBlock = nullptr;
1858 if ( requiresMultiPassRendering && deferredBlocks )
1859 {
1860 deferredBlocks->emplace_back( DeferredRenderBlock() );
1861 deferredBlock = &deferredBlocks->back();
1862 deferredBlock->fragments.reserve( block.size() );
1863 }
1864
1865 QgsScopedQPainterState painterState( context.painter() );
1867 context.painter()->translate( component.origin );
1868 if ( !qgsDoubleNear( rotation, 0.0 ) )
1869 context.painter()->rotate( rotation );
1870
1871 // apply to the mask painter the same transformations
1872 if ( maskPainter )
1873 {
1874 maskPainter->save();
1875 maskPainter->translate( component.origin );
1876 if ( !qgsDoubleNear( rotation, 0.0 ) )
1877 maskPainter->rotate( rotation );
1878 }
1879
1880 // figure x offset for horizontal alignment of multiple lines
1881 double xMultiLineOffset = 0.0;
1882 double blockWidth = metrics.blockWidth( blockIndex );
1883 double extraWordSpace = 0;
1884 double extraLetterSpace = 0;
1885 if ( adjustForAlignment )
1886 {
1887 double labelWidthDiff = 0;
1888 switch ( blockAlignment )
1889 {
1891 labelWidthDiff = ( targetWidth - blockWidth - metrics.blockLeftMargin( blockIndex ) - metrics.blockRightMargin( blockIndex ) ) * 0.5 + metrics.blockLeftMargin( blockIndex );
1892 break;
1893
1895 labelWidthDiff = targetWidth - blockWidth - metrics.blockRightMargin( blockIndex );
1896 break;
1897
1899 if ( !isFinalLineInParagraph && targetWidth > blockWidth )
1900 {
1901 calculateExtraSpacingForLineJustification( targetWidth - blockWidth, block, extraWordSpace, extraLetterSpace );
1902 blockWidth = targetWidth;
1903 }
1904 labelWidthDiff = metrics.blockLeftMargin( blockIndex );
1905 break;
1906
1908 labelWidthDiff = metrics.blockLeftMargin( blockIndex );
1909 break;
1910 }
1911
1912 switch ( mode )
1913 {
1918 xMultiLineOffset = labelWidthDiff;
1919 break;
1920
1922 {
1923 switch ( blockAlignment )
1924 {
1926 xMultiLineOffset = labelWidthDiff - targetWidth;
1927 break;
1928
1930 xMultiLineOffset = labelWidthDiff - targetWidth / 2.0;
1931 break;
1932
1935 xMultiLineOffset = metrics.blockLeftMargin( blockIndex );
1936 break;
1937 }
1938 }
1939 break;
1940 }
1941 }
1942 else if ( blockAlignment == Qgis::TextHorizontalAlignment::Left || blockAlignment == Qgis::TextHorizontalAlignment::Justify )
1943 {
1944 xMultiLineOffset = metrics.blockLeftMargin( blockIndex );
1945 }
1946
1947 const double baseLineOffset = metrics.baselineOffset( blockIndex, mode );
1948
1949 const QPointF blockOrigin( xMultiLineOffset, baseLineOffset + verticalAlignOffset );
1950 if ( deferredBlock )
1951 deferredBlock->origin = blockOrigin;
1952 else
1953 context.painter()->translate( blockOrigin );
1954 if ( maskPainter )
1955 maskPainter->translate( blockOrigin );
1956
1957 Component subComponent;
1958 subComponent.block = block;
1959 subComponent.blockIndex = blockIndex;
1960 subComponent.size = QSizeF( blockWidth, blockHeight );
1961 subComponent.offset = QPointF( 0.0, -metrics.ascentOffset() );
1962 subComponent.rotation = -component.rotation * 180 / M_PI;
1963 subComponent.rotationOffset = 0.0;
1964 subComponent.extraWordSpacing = extraWordSpace * fontScale;
1965 subComponent.extraLetterSpacing = extraLetterSpace * fontScale;
1966 if ( deferredBlock )
1967 deferredBlock->component = subComponent;
1968
1969 // draw the mask below the text (for preview)
1970 if ( format.mask().enabled() )
1971 {
1972 QgsTextRenderer::drawMask( context, subComponent, format, metrics, mode );
1973 }
1974
1975 if ( ( components & Qgis::TextComponent::Buffer )
1976 || ( components & Qgis::TextComponent::Text )
1977 || ( components & Qgis::TextComponent::Shadow ) )
1978 {
1979 // if we are drawing both text + buffer, we'll need a path, as we HAVE to render buffers using paths
1980 const bool needsPaths = usePathsForText
1981 || ( ( components & Qgis::TextComponent::Buffer ) && format.buffer().enabled() )
1982 || ( ( components & Qgis::TextComponent::Shadow ) && format.shadow().enabled() );
1983
1984 std::optional< QgsScopedRenderContextReferenceScaleOverride > referenceScaleOverride;
1985 if ( mode == Qgis::TextLayoutMode::Labeling )
1986 {
1987 // label size has already been calculated using any symbology reference scale factor -- we need
1988 // to temporarily remove the reference scale here or we'll be applying the scaling twice
1989 referenceScaleOverride.emplace( QgsScopedRenderContextReferenceScaleOverride( context, -1.0 ) );
1990 }
1991
1992 referenceScaleOverride.reset();
1993
1994 // now render the actual text
1995 if ( context.useAdvancedEffects() )
1996 {
1997 context.painter()->setCompositionMode( format.blendMode() );
1998 }
1999
2000 // scale for any print output or image saving @ specific dpi
2001 context.painter()->scale( subComponent.dpiRatio, subComponent.dpiRatio );
2002
2003 context.painter()->scale( 1 / fontScale, 1 / fontScale );
2004 context.painter()->setPen( Qt::NoPen );
2005 context.painter()->setBrush( Qt::NoBrush );
2006 renderBlockHorizontal( block, blockIndex, metrics, context, format, context.painter(), needsPaths,
2007 fontScale, extraWordSpace, extraLetterSpace, mode, deferredBlock );
2008 }
2009 if ( maskPainter )
2010 maskPainter->restore();
2011
2012 blockIndex++;
2013 }
2014
2015 if ( deferredBlocks )
2016 {
2017 renderDeferredBlocks(
2018 context, format, components, *deferredBlocks, usePathsForText, fontScale, component, rotation
2019 );
2020 }
2021}
2022
2023void QgsTextRenderer::renderDeferredBlocks( QgsRenderContext &context,
2024 const QgsTextFormat &format,
2025 Qgis::TextComponents components,
2026 const std::vector< DeferredRenderBlock > &deferredBlocks,
2027 bool usePathsForText,
2028 double fontScale,
2029 const Component &component,
2030 double rotation )
2031{
2032 if ( format.buffer().enabled() && ( components & Qgis::TextComponent::Buffer ) )
2033 {
2034 renderDeferredBuffer( context, format, components, deferredBlocks, fontScale, component, rotation );
2035 }
2036
2037 if ( ( components & Qgis::TextComponent::Shadow )
2038 && format.shadow().enabled()
2040 {
2041 renderDeferredShadowForText( context, format, deferredBlocks, fontScale, component, rotation );
2042 // TODO: there's an optimisation opportunity here -- if we are ALSO rendering the text component,
2043 // we could move the actual text rendering into renderDeferredShadowForText and use the same
2044 // QPicture as we used for the shadow. But we'd need to ensure that all the settings
2045 // which control whether text is rendered as text or paths also also considered.
2046 }
2047
2048 if ( components & Qgis::TextComponent::Text )
2049 {
2050 renderDeferredText( context, deferredBlocks, usePathsForText, fontScale, component, rotation );
2051 }
2052}
2053
2054void QgsTextRenderer::renderDeferredShadowForText( QgsRenderContext &context,
2055 const QgsTextFormat &format,
2056 const std::vector< DeferredRenderBlock > &deferredBlocks,
2057 double fontScale,
2058 const Component &component,
2059 double rotation )
2060{
2061 QgsScopedQPainterState painterState( context.painter() );
2063 context.painter()->translate( component.origin );
2064 if ( !qgsDoubleNear( rotation, 0.0 ) )
2065 context.painter()->rotate( rotation );
2066
2067 context.painter()->setPen( Qt::NoPen );
2068 context.painter()->setBrush( Qt::NoBrush );
2069
2070 for ( const DeferredRenderBlock &block : deferredBlocks )
2071 {
2072 Component subComponent = block.component;
2073
2074 QPainter painter( &subComponent.picture );
2075 painter.setPen( Qt::NoPen );
2076 painter.setBrush( Qt::NoBrush );
2077 painter.scale( 1 / fontScale, 1 / fontScale );
2078
2079 for ( const DeferredRenderFragment &fragment : std::as_const( block.fragments ) )
2080 {
2081 if ( !fragment.path.isEmpty() )
2082 {
2083 painter.setBrush( fragment.color );
2084 painter.drawPath( fragment.path );
2085 }
2086 else
2087 {
2088 painter.setPen( fragment.color );
2089 painter.setFont( fragment.font );
2090 painter.drawText( fragment.point, fragment.text );
2091 }
2092 }
2093 painter.end();
2094
2095 subComponent.pictureBuffer = 1.0; // no pen width to deal with, but we'll add 1 px for antialiasing
2096 subComponent.origin = QPointF( 0.0, 0.0 );
2097 const QRectF pictureBoundingRect = subComponent.picture.boundingRect();
2098 subComponent.size = pictureBoundingRect.size();
2099 subComponent.offset = QPointF( -pictureBoundingRect.left(), -pictureBoundingRect.height() - pictureBoundingRect.top() );
2100
2101 context.painter()->translate( block.origin );
2102 drawShadow( context, subComponent, format );
2103 context.painter()->translate( -block.origin );
2104 }
2105}
2106
2107void QgsTextRenderer::renderDeferredBuffer( QgsRenderContext &context,
2108 const QgsTextFormat &format,
2109 Qgis::TextComponents components,
2110 const std::vector< DeferredRenderBlock > &deferredBlocks,
2111 double fontScale,
2112 const Component &component,
2113 double rotation )
2114{
2115 QgsScopedQPainterState painterState( context.painter() );
2117
2118 // do we need a drop shadow effect on the buffer component? If so, we'll render the buffer to a QPicture first and then use this
2119 // to generate the shadow, and then render the QPicture as the buffer on top. If not, avoid the unwanted expense of the temporary QPicture
2120 // and render directly.
2121 const bool needsShadowOnBuffer = ( ( components & Qgis::TextComponent::Shadow ) && format.shadow().enabled() && format.shadow().shadowPlacement() == QgsTextShadowSettings::ShadowBuffer );
2122 std::unique_ptr< QPicture > bufferPicture;
2123 std::unique_ptr< QPainter > bufferPainter;
2124 QPainter *prevPainter = context.painter();
2125 if ( needsShadowOnBuffer )
2126 {
2127 bufferPicture = std::make_unique< QPicture >();
2128 bufferPainter = std::make_unique< QPainter >( bufferPicture.get() );
2129 context.setPainter( bufferPainter.get() );
2130 }
2131
2132 std::unique_ptr< QgsPaintEffect > tmpEffect;
2133 if ( format.buffer().paintEffect() && format.buffer().paintEffect()->enabled() )
2134 {
2135 tmpEffect.reset( format.buffer().paintEffect()->clone() );
2136 tmpEffect->begin( context );
2137 }
2138
2139 QColor bufferColor = format.buffer().color();
2140 bufferColor.setAlphaF( format.buffer().opacity() );
2141 QPen pen( bufferColor );
2142 const QgsTextBufferSettings &buffer = format.buffer();
2143 const double penSize = buffer.sizeUnit() == Qgis::RenderUnit::Percentage
2144 ? context.convertToPainterUnits( format.size(), format.sizeUnit(), format.sizeMapUnitScale() ) * buffer.size() / 100
2145 : context.convertToPainterUnits( buffer.size(), buffer.sizeUnit(), buffer.sizeMapUnitScale() );
2146 pen.setWidthF( penSize * fontScale );
2147 pen.setJoinStyle( buffer.joinStyle() );
2148 context.painter()->setPen( pen );
2149
2150 // honor pref for whether to fill buffer interior
2151 if ( !buffer.fillBufferInterior() )
2152 {
2153 bufferColor.setAlpha( 0 );
2154 }
2155 context.painter()->setBrush( bufferColor );
2156
2157 context.painter()->translate( component.origin );
2158 if ( !qgsDoubleNear( rotation, 0.0 ) )
2159 context.painter()->rotate( rotation );
2160
2161 if ( context.useAdvancedEffects() )
2162 {
2163 context.painter()->setCompositionMode( format.buffer().blendMode() );
2164 }
2165
2166 for ( const DeferredRenderBlock &block : deferredBlocks )
2167 {
2168 context.painter()->translate( block.origin );
2169 context.painter()->scale( 1 / fontScale, 1 / fontScale );
2170 for ( const DeferredRenderFragment &fragment : std::as_const( block.fragments ) )
2171 {
2172 context.painter()->drawPath( fragment.path );
2173 }
2174 context.painter()->scale( fontScale, fontScale );
2175 context.painter()->translate( -block.origin );
2176 }
2177
2178 if ( tmpEffect )
2179 {
2180 tmpEffect->end( context );
2181 }
2182
2183 if ( needsShadowOnBuffer && bufferPicture )
2184 {
2185 bufferPainter->end();
2186 bufferPainter.reset();
2187 context.setPainter( prevPainter );
2188
2189 QgsTextRenderer::Component bufferComponent = component;
2190 bufferComponent.origin = QPointF( 0.0, 0.0 );
2191 bufferComponent.picture = *bufferPicture;
2192 bufferComponent.pictureBuffer = penSize / 2.0;
2193 const QRectF bufferBoundingBox = bufferPicture->boundingRect();
2194 bufferComponent.size = bufferBoundingBox.size();
2195 bufferComponent.offset = QPointF( -bufferBoundingBox.left(), -bufferBoundingBox.height() - bufferBoundingBox.top() );
2196
2197 drawShadow( context, bufferComponent, format );
2198
2199 // also draw buffer
2200 if ( context.useAdvancedEffects() )
2201 {
2202 context.painter()->setCompositionMode( buffer.blendMode() );
2203 }
2204
2205 // scale for any print output or image saving @ specific dpi
2206 context.painter()->scale( component.dpiRatio, component.dpiRatio );
2207 QgsPainting::drawPicture( context.painter(), QPointF( 0, 0 ), *bufferPicture );
2208 }
2209}
2210
2211void QgsTextRenderer::renderDeferredText( QgsRenderContext &context,
2212 const std::vector< DeferredRenderBlock > &deferredBlocks,
2213 bool usePathsForText,
2214 double fontScale,
2215 const Component &component,
2216 double rotation )
2217{
2218 QgsScopedQPainterState painterState( context.painter() );
2220 context.painter()->translate( component.origin );
2221 if ( !qgsDoubleNear( rotation, 0.0 ) )
2222 context.painter()->rotate( rotation );
2223
2224 context.painter()->setPen( Qt::NoPen );
2225 context.painter()->setBrush( Qt::NoBrush );
2226
2227 // draw the text
2228 for ( const DeferredRenderBlock &block : deferredBlocks )
2229 {
2230 context.painter()->translate( block.origin );
2231 context.painter()->scale( 1 / fontScale, 1 / fontScale );
2232
2233 for ( const DeferredRenderFragment &fragment : std::as_const( block.fragments ) )
2234 {
2235 if ( usePathsForText )
2236 {
2237 context.painter()->setBrush( fragment.color );
2238 context.painter()->drawPath( fragment.path );
2239 }
2240 else
2241 {
2242 context.painter()->setPen( fragment.color );
2243 context.painter()->setFont( fragment.font );
2244 context.painter()->drawText( fragment.point, fragment.text );
2245 }
2246 }
2247
2248 context.painter()->scale( fontScale, fontScale );
2249 context.painter()->translate( -block.origin );
2250 }
2251}
2252
2253void QgsTextRenderer::drawTextInternalVertical( QgsRenderContext &context, const QgsTextFormat &format, Qgis::TextComponents components, Qgis::TextLayoutMode mode, const QgsTextRenderer::Component &component, const QgsTextDocument &document, const QgsTextDocumentMetrics &metrics, double fontScale, Qgis::TextHorizontalAlignment hAlignment, Qgis::TextVerticalAlignment, double rotation )
2254{
2255 QPainter *maskPainter = context.maskPainter( context.currentMaskId() );
2256 const QStringList textLines = document.toPlainText();
2257
2258 std::optional< QgsScopedRenderContextReferenceScaleOverride > referenceScaleOverride;
2259 if ( mode == Qgis::TextLayoutMode::Labeling )
2260 {
2261 // label size has already been calculated using any symbology reference scale factor -- we need
2262 // to temporarily remove the reference scale here or we'll be applying the scaling twice
2263 referenceScaleOverride.emplace( QgsScopedRenderContextReferenceScaleOverride( context, -1.0 ) );
2264 }
2265
2266 if ( metrics.isNullFontSize() )
2267 return;
2268
2269 referenceScaleOverride.reset();
2270
2271 const QSizeF documentSize = metrics.documentSize( mode, Qgis::TextOrientation::Vertical );
2272 const double actualTextWidth = documentSize.width();
2273 double textRectWidth = 0.0;
2274
2275 switch ( mode )
2276 {
2279 textRectWidth = actualTextWidth;
2280 break;
2281
2285 textRectWidth = component.size.width();
2286 break;
2287 }
2288
2289 int maxLineLength = 0;
2290 for ( const QString &line : std::as_const( textLines ) )
2291 {
2292 maxLineLength = std::max( maxLineLength, static_cast<int>( line.length() ) );
2293 }
2294
2295 const double actualLabelHeight = documentSize.height();
2296 int blockIndex = 0;
2297
2298 bool adjustForAlignment = hAlignment != Qgis::TextHorizontalAlignment::Left && ( mode != Qgis::TextLayoutMode::Labeling || textLines.size() > 1 );
2299
2300 for ( const QgsTextBlock &block : document )
2301 {
2302 QgsScopedQPainterState painterState( context.painter() );
2304
2305 context.painter()->translate( component.origin );
2306 if ( !qgsDoubleNear( rotation, 0.0 ) )
2307 context.painter()->rotate( rotation );
2308
2309 // apply to the mask painter the same transformations
2310 if ( maskPainter )
2311 {
2312 maskPainter->save();
2313 maskPainter->translate( component.origin );
2314 if ( !qgsDoubleNear( rotation, 0.0 ) )
2315 maskPainter->rotate( rotation );
2316 }
2317
2318 const double blockMaximumCharacterWidth = metrics.blockMaximumCharacterWidth( blockIndex );
2319
2320 // figure x offset of multiple lines
2321 double xOffset = metrics.verticalOrientationXOffset( blockIndex );
2322 if ( adjustForAlignment )
2323 {
2324 double hAlignmentOffset = 0;
2325 switch ( hAlignment )
2326 {
2328 hAlignmentOffset = ( textRectWidth - actualTextWidth ) * 0.5;
2329 break;
2330
2332 hAlignmentOffset = textRectWidth - actualTextWidth;
2333 break;
2334
2337 break;
2338 }
2339
2340 switch ( mode )
2341 {
2346 xOffset += hAlignmentOffset;
2347 break;
2348
2350 break;
2351 }
2352 }
2353
2354 double yOffset = 0.0;
2355 switch ( mode )
2356 {
2359 {
2360 if ( rotation >= -405 && rotation < -180 )
2361 {
2362 yOffset = 0;
2363 }
2364 else if ( rotation >= 0 && rotation < 45 )
2365 {
2366 xOffset -= actualTextWidth;
2367 yOffset = -actualLabelHeight + metrics.blockMaximumDescent( blockIndex );
2368 }
2369 }
2370 else
2371 {
2372 yOffset = -actualLabelHeight;
2373 }
2374 break;
2375
2377 yOffset = -actualLabelHeight;
2378 break;
2379
2383 yOffset = 0;
2384 break;
2385 }
2386
2387 context.painter()->translate( QPointF( xOffset, yOffset ) );
2388
2389 double currentBlockYOffset = 0;
2390 int fragmentIndex = 0;
2391 for ( const QgsTextFragment &fragment : block )
2392 {
2393 QgsScopedQPainterState fragmentPainterState( context.painter() );
2394
2395 // apply some character replacement to draw symbols in vertical presentation
2396 const QString line = QgsStringUtils::substituteVerticalCharacters( fragment.text() );
2397
2398 const QFont fragmentFont = metrics.fragmentFont( blockIndex, fragmentIndex );
2399
2400 QFontMetricsF fragmentMetrics( fragmentFont );
2401
2402 const double letterSpacing = fragmentFont.letterSpacing() / fontScale;
2403 const double labelHeight = fragmentMetrics.ascent() / fontScale + ( fragmentMetrics.ascent() / fontScale + letterSpacing ) * ( line.length() - 1 );
2404
2405 Component subComponent;
2406 subComponent.block = QgsTextBlock( fragment );
2407 subComponent.blockIndex = blockIndex;
2408 subComponent.firstFragmentIndex = fragmentIndex;
2409 subComponent.size = QSizeF( blockMaximumCharacterWidth, labelHeight + fragmentMetrics.descent() / fontScale );
2410 subComponent.offset = QPointF( 0.0, currentBlockYOffset );
2411 subComponent.rotation = -component.rotation * 180 / M_PI;
2412 subComponent.rotationOffset = 0.0;
2413
2414 // draw the mask below the text (for preview)
2415 if ( format.mask().enabled() )
2416 {
2417 // WARNING: totally broken! (has been since mask was introduced)
2418#if 0
2419 QgsTextRenderer::drawMask( context, subComponent, format );
2420#endif
2421 }
2422
2423 if ( components & Qgis::TextComponent::Buffer )
2424 {
2425 currentBlockYOffset += QgsTextRenderer::drawBuffer( context, subComponent, format, metrics, mode );
2426 }
2427 if ( ( components & Qgis::TextComponent::Text ) || ( components & Qgis::TextComponent::Shadow ) )
2428 {
2429 // draw text, QPainterPath method
2430 QPainterPath path;
2431 path.setFillRule( Qt::WindingFill );
2432 const QStringList parts = QgsPalLabeling::splitToGraphemes( fragment.text() );
2433 double partYOffset = 0.0;
2434 for ( const QString &part : parts )
2435 {
2436 double partXOffset = ( blockMaximumCharacterWidth - ( fragmentMetrics.horizontalAdvance( part ) / fontScale - letterSpacing ) ) / 2;
2437 partYOffset += fragmentMetrics.ascent() / fontScale;
2438 path.addText( partXOffset * fontScale, partYOffset * fontScale, fragmentFont, part );
2439 partYOffset += letterSpacing;
2440 }
2441
2442 // store text's drawing in QPicture for drop shadow call
2443 QPicture textPict;
2444 QPainter textp;
2445 textp.begin( &textPict );
2446 textp.setPen( Qt::NoPen );
2447 QColor textColor = fragment.characterFormat().textColor().isValid() ? fragment.characterFormat().textColor() : format.color();
2448 textColor.setAlphaF( fragment.characterFormat().textColor().isValid() ? textColor.alphaF() * format.opacity() : format.opacity() );
2449 textp.setBrush( textColor );
2450 textp.scale( 1 / fontScale, 1 / fontScale );
2451 textp.drawPath( path );
2452
2453 // TODO: why are some font settings lost on drawPicture() when using drawText() inside QPicture?
2454 // e.g. some capitalization options, but not others
2455 //textp.setFont( tmpLyr.textFont );
2456 //textp.setPen( tmpLyr.textColor );
2457 //textp.drawText( 0, 0, component.text() );
2458 textp.end();
2459
2460 if ( format.shadow().enabled() && format.shadow().shadowPlacement() == QgsTextShadowSettings::ShadowText )
2461 {
2462 subComponent.picture = textPict;
2463 subComponent.pictureBuffer = 0.0; // no pen width to deal with
2464 subComponent.origin = QPointF( 0.0, currentBlockYOffset );
2465 const double prevY = subComponent.offset.y();
2466 subComponent.offset = QPointF( 0, -subComponent.size.height() );
2467 subComponent.useOrigin = true;
2468 QgsTextRenderer::drawShadow( context, subComponent, format );
2469 subComponent.useOrigin = false;
2470 subComponent.offset = QPointF( 0, prevY );
2471 }
2472
2473 // paint the text
2474 if ( context.useAdvancedEffects() )
2475 {
2476 context.painter()->setCompositionMode( format.blendMode() );
2477 }
2478
2479 // scale for any print output or image saving @ specific dpi
2480 context.painter()->scale( subComponent.dpiRatio, subComponent.dpiRatio );
2481
2482 // TODO -- this should respect the context's TextRenderFormat
2483 // draw outlined text
2484 context.painter()->translate( 0, currentBlockYOffset );
2486 context.painter()->drawPicture( 0, 0, textPict );
2487 currentBlockYOffset += partYOffset;
2488 }
2489 fragmentIndex++;
2490 }
2491
2492 if ( maskPainter )
2493 maskPainter->restore();
2494 blockIndex++;
2495 }
2496}
2497
2499{
2501 return 1.0;
2502
2503 const double pixelSize = context.convertToPainterUnits( format.size(), format.sizeUnit(), format.sizeMapUnitScale() );
2504
2505 // THESE THRESHOLDS MAY NEED TWEAKING!
2506
2507 // NOLINTBEGIN(bugprone-branch-clone)
2508
2509 // for small font sizes we need to apply a growth scaling workaround designed to stablise the rendering of small font sizes
2510 // we scale the painter up so that we render small text at 200 pixel size and let the painter scaling handle making it the correct size
2511 if ( pixelSize < 50 )
2512 return 200 / pixelSize;
2513 //... but for large font sizes we might run into https://bugreports.qt.io/browse/QTBUG-98778, which messes up the spacing between words for large fonts!
2514 // so instead we scale down the painter so that we render the text at 200 pixel size and let painter scaling handle making it the correct size
2515 else if ( pixelSize > 200 )
2516 return 200 / pixelSize;
2517 else
2518 return 1.0;
2519
2520 // NOLINTEND(bugprone-branch-clone)
2521}
2522
TextLayoutMode
Text layout modes.
Definition qgis.h:2699
@ Labeling
Labeling-specific layout mode.
@ Point
Text at point of origin layout mode.
@ RectangleAscentBased
Similar to Rectangle mode, but uses ascents only when calculating font and line heights.
@ RectangleCapHeightBased
Similar to Rectangle mode, but uses cap height only when calculating font heights for the first line ...
@ Rectangle
Text within rectangle layout mode.
QFlags< TextRendererFlag > TextRendererFlags
Definition qgis.h:3162
TextOrientation
Text orientations.
Definition qgis.h:2684
@ Vertical
Vertically oriented text.
@ RotationBased
Horizontally or vertically oriented text based on rotation (only available for map labeling)
@ Horizontal
Horizontally oriented text.
@ Round
Use rounded joins.
@ Normal
Adjacent characters are positioned in the standard way for text in the writing system in use.
@ SubScript
Characters are placed below the base line for normal text.
@ SuperScript
Characters are placed above the base line for normal text.
@ PreferText
Render text as text objects, unless doing so results in rendering artifacts or poor quality rendering...
@ AlwaysOutlines
Always render text using path objects (AKA outlines/curves). This setting guarantees the best quality...
@ AlwaysText
Always render text as text objects. While this mode preserves text objects as text for post-processin...
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.
@ ApplyScalingWorkaroundForTextRendering
Whether a scaling workaround designed to stablise the rendering of small font sizes (or for painters ...
@ RenderBlocking
Render and load remote sources in the same thread to ensure rendering remote sources (svg and images)...
TextVerticalAlignment
Text vertical alignment.
Definition qgis.h:2759
@ Bottom
Align to bottom.
@ VerticalCenter
Center align.
QFlags< TextComponent > TextComponents
Text components.
Definition qgis.h:2729
TextHorizontalAlignment
Text horizontal alignment.
Definition qgis.h:2740
@ WrapLines
Automatically wrap long lines of text.
TextComponent
Text components.
Definition qgis.h:2716
@ Shadow
Drop shadow.
@ Buffer
Buffer component.
@ Text
Text component.
@ Background
Background shape.
static QgsImageCache * imageCache()
Returns the application's image cache, used for caching resampled versions of raster images.
A class to manager painter saving and restoring required for effect drawing.
QgsFeature feature() const
Convenience function for retrieving the feature for the context, if set.
QgsFields fields() const
Convenience function for retrieving the fields for the context, if set.
The feature class encapsulates a single feature including its unique ID, geometry and a list of field...
Definition qgsfeature.h:58
QgsFillSymbol * clone() const override
Returns a deep copy of this symbol.
Does vector analysis using the geos library and handles import, export, exception handling*.
Definition qgsgeos.h:137
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.
Line string geometry type, with support for z-dimension and m-values.
static QgsLineString * fromQPolygonF(const QPolygonF &polygon)
Returns a new linestring from a QPolygonF polygon input.
Struct for storing maximum and minimum scales for measurements in map units.
A marker symbol type, for rendering Point and MultiPoint geometries.
QgsMarkerSymbol * clone() const override
Returns a deep copy of this symbol.
bool enabled() const
Returns whether the effect is enabled.
virtual QgsPaintEffect * clone() const =0
Duplicates an effect by creating a deep copy of the effect.
A class to manage painter saving and restoring required for drawing on a different painter (mask pain...
static void applyScaleFixForQPictureDpi(QPainter *painter)
Applies a workaround to a painter to avoid an issue with incorrect scaling when drawing QPictures.
static void drawPicture(QPainter *painter, const QPointF &point, const QPicture &picture)
Draws a picture onto a painter, correctly applying workarounds to avoid issues with incorrect scaling...
static QStringList splitToGraphemes(const QString &text)
Splits a text string to a list of graphemes, which are the smallest allowable character divisions in ...
Contains precalculated properties regarding text metrics for text to be renderered at a later stage.
void setGraphemeFormats(const QVector< QgsTextCharacterFormat > &formats)
Sets the character formats associated with the text graphemes().
bool hasActiveProperties() const final
Returns true if the collection has any active properties, or false if all properties within the colle...
Contains information about the context of a rendering operation.
double scaleFactor() const
Returns the scaling factor for the render to convert painter units to physical sizes.
bool useAdvancedEffects() const
Returns true if advanced effects such as blend modes such be used.
void setScaleFactor(double factor)
Sets the scaling factor for the render to convert painter units to physical sizes.
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.
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.
bool isGuiPreview() const
Returns the Gui preview mode.
Qgis::TextRenderFormat textRenderFormat() const
Returns the text render format, which dictates how text is rendered (e.g.
const QgsMapToPixel & mapToPixel() const
Returns the context's map to pixel transform, which transforms between map coordinates and device coo...
QPainter * maskPainter(int id=0)
Returns a mask QPainter for the render operation.
void setMapToPixel(const QgsMapToPixel &mtp)
Sets the context's map to pixel transform, which transforms between map coordinates and device coordi...
int currentMaskId() const
Returns the current mask id, which can be used with maskPainter()
void setPainter(QPainter *p)
Sets the destination QPainter for the render operation.
Qgis::RenderContextFlags flags() const
Returns combination of flags used for rendering.
Scoped object for saving and restoring a QPainter object's state.
Scoped object for temporary override of the symbologyReferenceScale property of a QgsRenderContext.
static QString substituteVerticalCharacters(QString string)
Returns a string with characters having vertical representation form substituted.
static QgsSymbolLayer * create(const QVariantMap &properties=QVariantMap())
Creates the symbol.
void renderPoint(QPointF point, QgsSymbolRenderContext &context) override
Renders a marker at the specified point.
static void blurImageInPlace(QImage &image, QRect rect, int radius, bool alphaOnly)
Blurs an image in place, e.g. creating Qt-independent drop shadows.
static double estimateMaxSymbolBleed(QgsSymbol *symbol, const QgsRenderContext &context)
Returns the maximum estimated bleed for the symbol.
Container for settings relating to a text background object.
QgsMapUnitScale strokeWidthMapUnitScale() const
Returns the map unit scale object for the shape stroke width.
RotationType rotationType() const
Returns the method used for rotating the background shape.
QString svgFile() const
Returns the absolute path to the background SVG file, if set.
QSizeF size() const
Returns the size of the background shape.
QSizeF radii() const
Returns the radii used for rounding the corners of shapes.
QgsMapUnitScale radiiMapUnitScale() const
Returns the map unit scale object for the shape radii.
Qgis::RenderUnit radiiUnit() const
Returns the units used for the shape's radii.
QPainter::CompositionMode blendMode() const
Returns the blending mode used for drawing the background shape.
@ SizeBuffer
Shape size is determined by adding a buffer margin around text.
bool enabled() const
Returns whether the background is enabled.
double opacity() const
Returns the background shape's opacity.
double rotation() const
Returns the rotation for the background shape, in degrees clockwise.
QColor fillColor() const
Returns the color used for filing the background shape.
SizeType sizeType() const
Returns the method used to determine the size of the background shape (e.g., fixed size or buffer aro...
Qgis::RenderUnit strokeWidthUnit() const
Returns the units used for the shape's stroke width.
ShapeType type() const
Returns the type of background shape (e.g., square, ellipse, SVG).
double strokeWidth() const
Returns the width of the shape's stroke (stroke).
@ ShapeSquare
Square - buffered sizes only.
Qgis::RenderUnit offsetUnit() const
Returns the units used for the shape's offset.
QColor strokeColor() const
Returns the color used for outlining the background shape.
QgsFillSymbol * fillSymbol() const
Returns the fill symbol to be rendered in the background.
QgsMapUnitScale sizeMapUnitScale() const
Returns the map unit scale object for the shape size.
Qgis::RenderUnit sizeUnit() const
Returns the units used for the shape's size.
@ RotationOffset
Shape rotation is offset from text rotation.
@ RotationFixed
Shape rotation is a fixed angle.
QgsMarkerSymbol * markerSymbol() const
Returns the marker symbol to be rendered in the background.
const QgsPaintEffect * paintEffect() const
Returns the current paint effect for the background shape.
QgsMapUnitScale offsetMapUnitScale() const
Returns the map unit scale object for the shape offset.
QPointF offset() const
Returns the offset used for drawing the background shape.
Qgis::TextHorizontalAlignment horizontalAlignment() const
Returns the format horizontal alignment.
bool hasHorizontalAlignmentSet() const
Returns true if the format has an explicit horizontal alignment set.
Represents a block of text consisting of one or more QgsTextFragment objects.
int size() const
Returns the number of fragments in the block.
QString toPlainText() const
Converts the block to plain text.
const QgsTextBlockFormat & blockFormat() const
Returns the block formatting for the fragment.
Container for settings relating to a text buffer.
Qgis::RenderUnit sizeUnit() const
Returns the units for the buffer size.
Qt::PenJoinStyle joinStyle() const
Returns the buffer join style.
double size() const
Returns the size of the buffer.
QgsMapUnitScale sizeMapUnitScale() const
Returns the map unit scale object for the buffer size.
bool enabled() const
Returns whether the buffer is enabled.
double opacity() const
Returns the buffer opacity.
bool fillBufferInterior() const
Returns whether the interior of the buffer will be filled in.
const QgsPaintEffect * paintEffect() const
Returns the current paint effect for the buffer.
QColor color() const
Returns the color of the buffer.
QPainter::CompositionMode blendMode() const
Returns the blending mode used for drawing the buffer.
Stores information relating to individual character formatting.
void updateFontForFormat(QFont &font, const QgsRenderContext &context, double scaleFactor=1.0) const
Updates the specified font in place, applying character formatting options which are applicable on a ...
Qgis::TextCharacterVerticalAlignment verticalAlignment() const
Returns the format vertical alignment.
bool hasVerticalAlignmentSet() const
Returns true if the format has an explicit vertical alignment set.
double fontPointSize() const
Returns the font point size, or -1 if the font size is not set and should be inherited.
Contains pre-calculated metrics of a QgsTextDocument.
double verticalOrientationXOffset(int blockIndex) const
Returns the vertical orientation x offset for the specified block.
double fragmentVerticalOffset(int blockIndex, int fragmentIndex, Qgis::TextLayoutMode mode) const
Returns the vertical offset from a text block's baseline which should be applied to the fragment at t...
double blockMaximumDescent(int blockIndex) const
Returns the maximum descent encountered in the specified block.
QSizeF documentSize(Qgis::TextLayoutMode mode, Qgis::TextOrientation orientation) const
Returns the overall size of the document.
double blockRightMargin(int blockIndex) const
Returns the margin for the right side of the specified block index.
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...
QFont fragmentFont(int blockIndex, int fragmentIndex) const
Returns the calculated font for the fragment at the specified block and fragment indices.
double blockMaximumCharacterWidth(int blockIndex) const
Returns the maximum character width for the specified block.
double baselineOffset(int blockIndex, Qgis::TextLayoutMode mode) const
Returns the offset from the top of the document to the text baseline for the given block index.
double fragmentFixedHeight(int blockIndex, int fragmentIndex, Qgis::TextLayoutMode mode) const
Returns the fixed height of the fragment at the specified block and fragment index,...
double blockLeftMargin(int blockIndex) const
Returns the margin for the left side of the specified block index.
double blockHeight(int blockIndex) const
Returns the height of the block at the specified index.
double fragmentHorizontalAdvance(int blockIndex, int fragmentIndex, Qgis::TextLayoutMode mode) const
Returns the horizontal advance of the fragment at the specified block and fragment index.
bool isNullFontSize() const
Returns true if the metrics could not be calculated because the text format has a null font size.
const QgsTextDocument & document() const
Returns the document associated with the calculated metrics.
double blockWidth(int blockIndex) const
Returns the width of the block at the specified index.
double ascentOffset() const
Returns the ascent offset of the first block in the document.
double blockVerticalMargin(int blockIndex) const
Returns the vertical margin for the specified block index.
Encapsulates the context in which a text document is to be rendered.
void setFlags(Qgis::TextRendererFlags flags)
Sets associated text renderer flags.
void setMaximumWidth(double width)
Sets the maximum width (in painter units) for rendered text.
Represents a document consisting of one or more QgsTextBlock objects.
const QgsTextBlock & at(int index) const
Returns the block at the specified index.
QStringList toPlainText() const
Returns a list of plain text lines of text representing the document.
int size() const
Returns the number of blocks in the document.
void append(const QgsTextBlock &block)
Appends a block to the document.
static QgsTextDocument fromTextAndFormat(const QStringList &lines, const QgsTextFormat &format)
Constructor for QgsTextDocument consisting of a set of lines, respecting settings from a text format.
void applyCapitalization(Qgis::Capitalization capitalization)
Applies a capitalization style to the document's text.
Container for all settings relating to text rendering.
QgsMapUnitScale sizeMapUnitScale() const
Returns the map unit scale object for the size.
void updateDataDefinedProperties(QgsRenderContext &context)
Updates the format by evaluating current values of data defined properties.
QgsPropertyCollection & dataDefinedProperties()
Returns a reference to the format's property collection, used for data defined overrides.
QFont scaledFont(const QgsRenderContext &context, double scaleFactor=1.0, bool *isZeroSize=nullptr) const
Returns a font with the size scaled to match the format's size settings (including units and map unit...
QPainter::CompositionMode blendMode() const
Returns the blending mode used for drawing the text.
Qgis::Capitalization capitalization() const
Returns the text capitalization style.
QgsTextMaskSettings & mask()
Returns a reference to the masking settings.
QgsTextBackgroundSettings & background()
Returns a reference to the text background settings.
Qgis::RenderUnit sizeUnit() const
Returns the units for the size of rendered text.
double opacity() const
Returns the text's opacity.
Qgis::TextOrientation orientation() const
Returns the orientation of the text.
double size() const
Returns the size for rendered text.
QgsTextShadowSettings & shadow()
Returns a reference to the text drop shadow settings.
QColor color() const
Returns the color that text will be rendered in.
QFont font() const
Returns the font used for rendering text.
QgsTextBufferSettings & buffer()
Returns a reference to the text buffer settings.
Stores a fragment of document along with formatting overrides to be used when rendering the fragment.
Container for settings relating to a selective masking around a text.
Qgis::RenderUnit sizeUnit() const
Returns the units for the buffer size.
QgsMapUnitScale sizeMapUnitScale() const
Returns the map unit scale object for the buffer size.
double size() const
Returns the size of the buffer.
QgsPaintEffect * paintEffect() const
Returns the current paint effect for the mask.
double opacity() const
Returns the mask's opacity.
bool enabled() const
Returns whether the mask is enabled.
Qt::PenJoinStyle joinStyle() const
Returns the buffer join style.
Contains placement information for a single grapheme in a curved text layout.
@ RespectPainterOrientation
Curved text will be placed respecting the painter orientation, and the actual line direction will be ...
@ TruncateStringWhenLineIsTooShort
When a string is too long for the line, truncate characters instead of aborting the placement.
@ UseBaselinePlacement
Generate placement based on the character baselines instead of centers.
static std::unique_ptr< CurvePlacementProperties > generateCurvedTextPlacement(const QgsPrecalculatedTextMetrics &metrics, const QPolygonF &line, double offsetAlongLine, LabelLineDirection direction=RespectPainterOrientation, double maxConcaveAngle=-1, double maxConvexAngle=-1, CurvedTextFlags flags=CurvedTextFlags())
Calculates curved text placement properties.
static void drawDocumentOnLine(const QPolygonF &line, const QgsTextFormat &format, const QgsTextDocument &document, QgsRenderContext &context, double offsetAlongLine=0, double offsetFromLine=0)
Draws a text document along a line using the specified settings.
static Qgis::TextVerticalAlignment convertQtVAlignment(Qt::Alignment alignment)
Converts a Qt vertical alignment flag to a Qgis::TextVerticalAlignment value.
static double textWidth(const QgsRenderContext &context, const QgsTextFormat &format, const QStringList &textLines, QFontMetricsF *fontMetrics=nullptr)
Returns the width of a text based on a given format.
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.
static int sizeToPixel(double size, const QgsRenderContext &c, Qgis::RenderUnit unit, const QgsMapUnitScale &mapUnitScale=QgsMapUnitScale())
Calculates pixel size (considering output size should be in pixel or map units, scale factors and opt...
static Q_DECL_DEPRECATED void drawPart(const QRectF &rect, double rotation, Qgis::TextHorizontalAlignment alignment, const QStringList &textLines, QgsRenderContext &context, const QgsTextFormat &format, Qgis::TextComponent part, bool drawAsOutlines=true)
Draws a single component of rendered text using the specified settings.
static void drawText(const QRectF &rect, double rotation, Qgis::TextHorizontalAlignment alignment, const QStringList &textLines, QgsRenderContext &context, const QgsTextFormat &format, bool drawAsOutlines=true, Qgis::TextVerticalAlignment vAlignment=Qgis::TextVerticalAlignment::Top, Qgis::TextRendererFlags flags=Qgis::TextRendererFlags(), Qgis::TextLayoutMode mode=Qgis::TextLayoutMode::Rectangle)
Draws text within a rectangle using the specified settings.
static bool textRequiresWrapping(const QgsRenderContext &context, const QString &text, double width, const QgsTextFormat &format)
Returns true if the specified text requires line wrapping in order to fit within the specified width ...
static QFontMetricsF fontMetrics(QgsRenderContext &context, const QgsTextFormat &format, double scaleFactor=1.0)
Returns the font metrics for the given text format, when rendered in the specified render context.
static void drawTextOnLine(const QPolygonF &line, const QString &text, QgsRenderContext &context, const QgsTextFormat &format, double offsetAlongLine=0, double offsetFromLine=0)
Draws text along a line using the specified settings.
static double calculateScaleFactorForFormat(const QgsRenderContext &context, const QgsTextFormat &format)
Returns the scale factor used for upscaling font sizes and downscaling destination painter devices.
static QStringList wrappedText(const QgsRenderContext &context, const QString &text, double width, const QgsTextFormat &format)
Wraps a text string to multiple lines, such that each individual line will fit within the specified w...
static double textHeight(const QgsRenderContext &context, const QgsTextFormat &format, const QStringList &textLines, Qgis::TextLayoutMode mode=Qgis::TextLayoutMode::Point, QFontMetricsF *fontMetrics=nullptr, Qgis::TextRendererFlags flags=Qgis::TextRendererFlags(), double maxLineWidth=0)
Returns the height of a text based on a given format.
static constexpr double SUPERSCRIPT_SUBSCRIPT_FONT_SIZE_SCALING_FACTOR
Scale factor to use for super or subscript text which doesn't have an explicit font size set.
static Qgis::TextHorizontalAlignment convertQtHAlignment(Qt::Alignment alignment)
Converts a Qt horizontal alignment flag to a Qgis::TextHorizontalAlignment value.
Container for settings relating to a text shadow.
int offsetAngle() const
Returns the angle for offsetting the position of the shadow from the text.
bool enabled() const
Returns whether the shadow is enabled.
int scale() const
Returns the scaling used for the drop shadow (in percentage of original size).
Qgis::RenderUnit offsetUnit() const
Returns the units used for the shadow's offset.
void setShadowPlacement(QgsTextShadowSettings::ShadowPlacement placement)
Sets the placement for the drop shadow.
double opacity() const
Returns the shadow's opacity.
QgsMapUnitScale blurRadiusMapUnitScale() const
Returns the map unit scale object for the shadow blur radius.
QColor color() const
Returns the color of the drop shadow.
@ ShadowBuffer
Draw shadow under buffer.
@ ShadowShape
Draw shadow under background shape.
@ ShadowLowest
Draw shadow below all text components.
@ ShadowText
Draw shadow under text.
QgsTextShadowSettings::ShadowPlacement shadowPlacement() const
Returns the placement for the drop shadow.
Qgis::RenderUnit blurRadiusUnit() const
Returns the units used for the shadow's blur radius.
double offsetDistance() const
Returns the distance for offsetting the position of the shadow from the text.
QPainter::CompositionMode blendMode() const
Returns the blending mode used for drawing the drop shadow.
QgsMapUnitScale offsetMapUnitScale() const
Returns the map unit scale object for the shadow offset distance.
bool blurAlphaOnly() const
Returns whether only the alpha channel for the shadow will be blurred.
bool offsetGlobal() const
Returns true if the global shadow offset will be used.
double blurRadius() const
Returns the blur radius for the shadow.
static Q_INVOKABLE QString encodeUnit(Qgis::DistanceUnit unit)
Encodes a distance unit to a string.
double ANALYSIS_EXPORT angle(QgsPoint *p1, QgsPoint *p2, QgsPoint *p3, QgsPoint *p4)
Calculates the angle between two segments (in 2 dimension, z-values are ignored)
Contains geos related utilities and functions.
Definition qgsgeos.h:75
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
#define BUILTIN_UNREACHABLE
Definition qgis.h:6612
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
const char * finder(const char *name)
QList< QgsSymbolLayer * > QgsSymbolLayerList
Definition qgssymbol.h:30