QGIS API Documentation  3.2.0-Bonn (bc43194)
qgslayoututils.cpp
Go to the documentation of this file.
1 /***************************************************************************
2  qgslayoututils.cpp
3  ------------------
4  begin : July 2017
5  copyright : (C) 2017 by Nyall Dawson
6  email : nyall dot dawson at gmail dot com
7  ***************************************************************************/
8 
9 /***************************************************************************
10  * *
11  * This program is free software; you can redistribute it and/or modify *
12  * it under the terms of the GNU General Public License as published by *
13  * the Free Software Foundation; either version 2 of the License, or *
14  * (at your option) any later version. *
15  * *
16  ***************************************************************************/
17 
18 #include "qgslayoututils.h"
19 #include "qgslayout.h"
20 #include "qgsrendercontext.h"
21 #include "qgslayoutitemmap.h"
22 #include <QStyleOptionGraphicsItem>
23 #include <QPainter>
24 #include <cmath>
25 
26 #ifndef M_DEG2RAD
27 #define M_DEG2RAD 0.0174532925
28 #endif
29 
30 void QgsLayoutUtils::rotate( double angle, double &x, double &y )
31 {
32  double rotToRad = angle * M_PI / 180.0;
33  double xRot, yRot;
34  xRot = x * std::cos( rotToRad ) - y * std::sin( rotToRad );
35  yRot = x * std::sin( rotToRad ) + y * std::cos( rotToRad );
36  x = xRot;
37  y = yRot;
38 }
39 
40 double QgsLayoutUtils::normalizedAngle( const double angle, const bool allowNegative )
41 {
42  double clippedAngle = angle;
43  if ( clippedAngle >= 360.0 || clippedAngle <= -360.0 )
44  {
45  clippedAngle = std::fmod( clippedAngle, 360.0 );
46  }
47  if ( !allowNegative && clippedAngle < 0.0 )
48  {
49  clippedAngle += 360.0;
50  }
51  return clippedAngle;
52 }
53 
55 {
56  //normalize angle to 0-360 degrees
57  double clippedAngle = normalizedAngle( angle );
58 
59  //snap angle to 45 degree
60  if ( clippedAngle >= 22.5 && clippedAngle < 67.5 )
61  {
62  return 45.0;
63  }
64  else if ( clippedAngle >= 67.5 && clippedAngle < 112.5 )
65  {
66  return 90.0;
67  }
68  else if ( clippedAngle >= 112.5 && clippedAngle < 157.5 )
69  {
70  return 135.0;
71  }
72  else if ( clippedAngle >= 157.5 && clippedAngle < 202.5 )
73  {
74  return 180.0;
75  }
76  else if ( clippedAngle >= 202.5 && clippedAngle < 247.5 )
77  {
78  return 225.0;
79  }
80  else if ( clippedAngle >= 247.5 && clippedAngle < 292.5 )
81  {
82  return 270.0;
83  }
84  else if ( clippedAngle >= 292.5 && clippedAngle < 337.5 )
85  {
86  return 315.0;
87  }
88  else
89  {
90  return 0.0;
91  }
92 }
93 
95 {
96  if ( !map )
97  {
98  QgsRenderContext context;
99  context.setPainter( painter );
100  if ( dpi < 0 && painter && painter->device() )
101  {
102  context.setScaleFactor( painter->device()->logicalDpiX() / 25.4 );
103  }
104  else if ( dpi > 0 )
105  {
106  context.setScaleFactor( dpi / 25.4 );
107  }
108  else
109  {
110  context.setScaleFactor( 3.465 ); //assume 88 dpi as standard value
111  }
112  return context;
113  }
114  else
115  {
116  // default to 88 dpi if no painter specified
117  if ( dpi < 0 )
118  {
119  dpi = ( painter && painter->device() ) ? painter->device()->logicalDpiX() : 88;
120  }
121  double dotsPerMM = dpi / 25.4;
122 
123  // get map settings from reference map
124  QgsRectangle extent = map->extent();
125  QSizeF mapSizeLayoutUnits = map->rect().size();
126  QSizeF mapSizeMM = map->layout()->convertFromLayoutUnits( mapSizeLayoutUnits, QgsUnitTypes::LayoutMillimeters ).toQSizeF();
127  QgsMapSettings ms = map->mapSettings( extent, mapSizeMM * dotsPerMM, dpi, false );
129  if ( painter )
130  context.setPainter( painter );
131 
132  context.setFlags( map->layout()->renderContext().renderContextFlags() );
133  return context;
134  }
135 }
136 
138 {
139  QgsLayoutItemMap *referenceMap = layout ? layout->referenceMap() : nullptr;
140  QgsRenderContext context = createRenderContextForMap( referenceMap, painter, dpi );
141  if ( layout )
142  context.setFlags( layout->renderContext().renderContextFlags() );
143  return context;
144 }
145 
146 void QgsLayoutUtils::relativeResizeRect( QRectF &rectToResize, const QRectF &boundsBefore, const QRectF &boundsAfter )
147 {
148  //linearly scale rectToResize relative to the scaling from boundsBefore to boundsAfter
149  double left = relativePosition( rectToResize.left(), boundsBefore.left(), boundsBefore.right(), boundsAfter.left(), boundsAfter.right() );
150  double right = relativePosition( rectToResize.right(), boundsBefore.left(), boundsBefore.right(), boundsAfter.left(), boundsAfter.right() );
151  double top = relativePosition( rectToResize.top(), boundsBefore.top(), boundsBefore.bottom(), boundsAfter.top(), boundsAfter.bottom() );
152  double bottom = relativePosition( rectToResize.bottom(), boundsBefore.top(), boundsBefore.bottom(), boundsAfter.top(), boundsAfter.bottom() );
153 
154  rectToResize.setRect( left, top, right - left, bottom - top );
155 }
156 
157 double QgsLayoutUtils::relativePosition( const double position, const double beforeMin, const double beforeMax, const double afterMin, const double afterMax )
158 {
159  //calculate parameters for linear scale between before and after ranges
160  double m = ( afterMax - afterMin ) / ( beforeMax - beforeMin );
161  double c = afterMin - ( beforeMin * m );
162 
163  //return linearly scaled position
164  return m * position + c;
165 }
166 QFont QgsLayoutUtils::scaledFontPixelSize( const QFont &font )
167 {
168  //upscale using FONT_WORKAROUND_SCALE
169  //ref: http://osgeo-org.1560.x6.nabble.com/Multi-line-labels-and-font-bug-td4157152.html
170  QFont scaledFont = font;
171  double pixelSize = pointsToMM( scaledFont.pointSizeF() ) * FONT_WORKAROUND_SCALE + 0.5;
172  scaledFont.setPixelSize( pixelSize );
173  return scaledFont;
174 }
175 
176 double QgsLayoutUtils::fontAscentMM( const QFont &font )
177 {
178  //upscale using FONT_WORKAROUND_SCALE
179  //ref: http://osgeo-org.1560.x6.nabble.com/Multi-line-labels-and-font-bug-td4157152.html
180  QFont metricsFont = scaledFontPixelSize( font );
181  QFontMetricsF fontMetrics( metricsFont );
182  return ( fontMetrics.ascent() / FONT_WORKAROUND_SCALE );
183 }
184 
185 double QgsLayoutUtils::fontDescentMM( const QFont &font )
186 {
187  //upscale using FONT_WORKAROUND_SCALE
188  //ref: http://osgeo-org.1560.x6.nabble.com/Multi-line-labels-and-font-bug-td4157152.html
189  QFont metricsFont = scaledFontPixelSize( font );
190  QFontMetricsF fontMetrics( metricsFont );
191  return ( fontMetrics.descent() / FONT_WORKAROUND_SCALE );
192 
193 }
194 
195 double QgsLayoutUtils::fontHeightMM( const QFont &font )
196 {
197  //upscale using FONT_WORKAROUND_SCALE
198  //ref: http://osgeo-org.1560.x6.nabble.com/Multi-line-labels-and-font-bug-td4157152.html
199  QFont metricsFont = scaledFontPixelSize( font );
200  QFontMetricsF fontMetrics( metricsFont );
201  return ( fontMetrics.height() / FONT_WORKAROUND_SCALE );
202 
203 }
204 
205 double QgsLayoutUtils::fontHeightCharacterMM( const QFont &font, QChar character )
206 {
207  //upscale using FONT_WORKAROUND_SCALE
208  //ref: http://osgeo-org.1560.x6.nabble.com/Multi-line-labels-and-font-bug-td4157152.html
209  QFont metricsFont = scaledFontPixelSize( font );
210  QFontMetricsF fontMetrics( metricsFont );
211  return ( fontMetrics.boundingRect( character ).height() / FONT_WORKAROUND_SCALE );
212 }
213 
214 double QgsLayoutUtils::textWidthMM( const QFont &font, const QString &text )
215 {
216  //upscale using FONT_WORKAROUND_SCALE
217  //ref: http://osgeo-org.1560.x6.nabble.com/Multi-line-labels-and-font-bug-td4157152.html
218  QFont metricsFont = scaledFontPixelSize( font );
219  QFontMetricsF fontMetrics( metricsFont );
220  return ( fontMetrics.width( text ) / FONT_WORKAROUND_SCALE );
221 }
222 
223 double QgsLayoutUtils::textHeightMM( const QFont &font, const QString &text, double multiLineHeight )
224 {
225  QStringList multiLineSplit = text.split( '\n' );
226  int lines = multiLineSplit.size();
227 
228  //upscale using FONT_WORKAROUND_SCALE
229  //ref: http://osgeo-org.1560.x6.nabble.com/Multi-line-labels-and-font-bug-td4157152.html
230  QFont metricsFont = scaledFontPixelSize( font );
231  QFontMetricsF fontMetrics( metricsFont );
232 
233  double fontHeight = fontMetrics.ascent() + fontMetrics.descent(); // ignore +1 for baseline
234  double textHeight = fontMetrics.ascent() + static_cast< double >( ( lines - 1 ) * fontHeight * multiLineHeight );
235 
236  return textHeight / FONT_WORKAROUND_SCALE;
237 }
238 
239 void QgsLayoutUtils::drawText( QPainter *painter, QPointF position, const QString &text, const QFont &font, const QColor &color )
240 {
241  if ( !painter )
242  {
243  return;
244  }
245 
246  //upscale using FONT_WORKAROUND_SCALE
247  //ref: http://osgeo-org.1560.x6.nabble.com/Multi-line-labels-and-font-bug-td4157152.html
248  QFont textFont = scaledFontPixelSize( font );
249 
250  painter->save();
251  painter->setFont( textFont );
252  if ( color.isValid() )
253  {
254  painter->setPen( color );
255  }
256  double scaleFactor = 1.0 / FONT_WORKAROUND_SCALE;
257  painter->scale( scaleFactor, scaleFactor );
258  painter->drawText( position * FONT_WORKAROUND_SCALE, text );
259  painter->restore();
260 }
261 
262 void QgsLayoutUtils::drawText( QPainter *painter, const QRectF &rect, const QString &text, const QFont &font, const QColor &color, const Qt::AlignmentFlag halignment, const Qt::AlignmentFlag valignment, const int flags )
263 {
264  if ( !painter )
265  {
266  return;
267  }
268 
269  //upscale using FONT_WORKAROUND_SCALE
270  //ref: http://osgeo-org.1560.x6.nabble.com/Multi-line-labels-and-font-bug-td4157152.html
271  QFont textFont = scaledFontPixelSize( font );
272 
273  QRectF scaledRect( rect.x() * FONT_WORKAROUND_SCALE, rect.y() * FONT_WORKAROUND_SCALE,
274  rect.width() * FONT_WORKAROUND_SCALE, rect.height() * FONT_WORKAROUND_SCALE );
275 
276  painter->save();
277  painter->setFont( textFont );
278  if ( color.isValid() )
279  {
280  painter->setPen( color );
281  }
282  double scaleFactor = 1.0 / FONT_WORKAROUND_SCALE;
283  painter->scale( scaleFactor, scaleFactor );
284  painter->drawText( scaledRect, halignment | valignment | flags, text );
285  painter->restore();
286 }
287 
288 QRectF QgsLayoutUtils::largestRotatedRectWithinBounds( const QRectF &originalRect, const QRectF &boundsRect, const double rotation )
289 {
290  double originalWidth = originalRect.width();
291  double originalHeight = originalRect.height();
292  double boundsWidth = boundsRect.width();
293  double boundsHeight = boundsRect.height();
294  double ratioBoundsRect = boundsWidth / boundsHeight;
295 
296  double clippedRotation = normalizedAngle( rotation );
297 
298  //shortcut for some rotation values
299  if ( qgsDoubleNear( clippedRotation, 0.0 ) || qgsDoubleNear( clippedRotation, 90.0 ) || qgsDoubleNear( clippedRotation, 180.0 ) || qgsDoubleNear( clippedRotation, 270.0 ) )
300  {
301  double rectScale;
302  if ( qgsDoubleNear( clippedRotation, 0.0 ) || qgsDoubleNear( clippedRotation, 180.0 ) )
303  {
304  rectScale = ( ( originalWidth / originalHeight ) > ratioBoundsRect ) ? boundsWidth / originalWidth : boundsHeight / originalHeight;
305  }
306  else
307  {
308  rectScale = ( ( originalHeight / originalWidth ) > ratioBoundsRect ) ? boundsWidth / originalHeight : boundsHeight / originalWidth;
309  }
310  double rectScaledWidth = rectScale * originalWidth;
311  double rectScaledHeight = rectScale * originalHeight;
312 
313  if ( qgsDoubleNear( clippedRotation, 0.0 ) || qgsDoubleNear( clippedRotation, 180.0 ) )
314  {
315  return QRectF( ( boundsWidth - rectScaledWidth ) / 2.0, ( boundsHeight - rectScaledHeight ) / 2.0, rectScaledWidth, rectScaledHeight );
316  }
317  else
318  {
319  return QRectF( ( boundsWidth - rectScaledHeight ) / 2.0, ( boundsHeight - rectScaledWidth ) / 2.0, rectScaledWidth, rectScaledHeight );
320  }
321  }
322 
323  //convert angle to radians and flip
324  double angleRad = -clippedRotation * M_DEG2RAD;
325  double cosAngle = std::cos( angleRad );
326  double sinAngle = std::sin( angleRad );
327 
328  //calculate size of bounds of rotated rectangle
329  double widthBoundsRotatedRect = originalWidth * std::fabs( cosAngle ) + originalHeight * std::fabs( sinAngle );
330  double heightBoundsRotatedRect = originalHeight * std::fabs( cosAngle ) + originalWidth * std::fabs( sinAngle );
331 
332  //compare ratio of rotated rect with bounds rect and calculate scaling of rotated
333  //rect to fit within bounds
334  double ratioBoundsRotatedRect = widthBoundsRotatedRect / heightBoundsRotatedRect;
335  double rectScale = ratioBoundsRotatedRect > ratioBoundsRect ? boundsWidth / widthBoundsRotatedRect : boundsHeight / heightBoundsRotatedRect;
336  double rectScaledWidth = rectScale * originalWidth;
337  double rectScaledHeight = rectScale * originalHeight;
338 
339  //now calculate offset so that rotated rectangle is centered within bounds
340  //first calculate min x and y coordinates
341  double currentCornerX = 0;
342  double minX = 0;
343  currentCornerX += rectScaledWidth * cosAngle;
344  minX = minX < currentCornerX ? minX : currentCornerX;
345  currentCornerX += rectScaledHeight * sinAngle;
346  minX = minX < currentCornerX ? minX : currentCornerX;
347  currentCornerX -= rectScaledWidth * cosAngle;
348  minX = minX < currentCornerX ? minX : currentCornerX;
349 
350  double currentCornerY = 0;
351  double minY = 0;
352  currentCornerY -= rectScaledWidth * sinAngle;
353  minY = minY < currentCornerY ? minY : currentCornerY;
354  currentCornerY += rectScaledHeight * cosAngle;
355  minY = minY < currentCornerY ? minY : currentCornerY;
356  currentCornerY += rectScaledWidth * sinAngle;
357  minY = minY < currentCornerY ? minY : currentCornerY;
358 
359  //now calculate offset position of rotated rectangle
360  double offsetX = ratioBoundsRotatedRect > ratioBoundsRect ? 0 : ( boundsWidth - rectScale * widthBoundsRotatedRect ) / 2.0;
361  offsetX += std::fabs( minX );
362  double offsetY = ratioBoundsRotatedRect > ratioBoundsRect ? ( boundsHeight - rectScale * heightBoundsRotatedRect ) / 2.0 : 0;
363  offsetY += std::fabs( minY );
364 
365  return QRectF( offsetX, offsetY, rectScaledWidth, rectScaledHeight );
366 }
367 
369 {
370  QString s = string.trimmed();
371  if ( s.compare( QLatin1String( "Portrait" ), Qt::CaseInsensitive ) == 0 )
372  {
373  ok = true;
375  }
376  else if ( s.compare( QLatin1String( "Landscape" ), Qt::CaseInsensitive ) == 0 )
377  {
378  ok = true;
380  }
381  ok = false;
382  return QgsLayoutItemPage::Landscape; // default to landscape
383 }
384 
385 double QgsLayoutUtils::scaleFactorFromItemStyle( const QStyleOptionGraphicsItem *style )
386 {
387  // workaround Qt bug 66185
388 
389  // Refs #18027 - if a QGraphicsItem is rotated by 90 or 270 degrees, then the item
390  // style given to QGraphicsItem::paint incorrectly uses the shear parameter of the matrix (m12)
391  // to store the current view scale, instead of the horizontal scale parameter (m11) which
392  // is used in all other cases
393 
394  // TODO - ifdef this out if Qt fixes upstream
395  return !qgsDoubleNear( style->matrix.m11(), 0.0 ) ? style->matrix.m11() : style->matrix.m12();
396 }
397 
398 QgsMapLayer *QgsLayoutUtils::mapLayerFromString( const QString &string, QgsProject *project )
399 {
400  // Maybe it's a layer id?
401  if ( QgsMapLayer *ml = project->mapLayer( string ) )
402  return ml;
403 
404  // Still nothing? Check for layer name
405  if ( QgsMapLayer *ml = project->mapLayersByName( string ).value( 0 ) )
406  return ml;
407 
408  // Still nothing? Check for layer name, case-insensitive
409  const auto layers = project->mapLayers();
410  for ( auto it = layers.constBegin(); it != layers.constEnd(); ++it )
411  {
412  if ( it.value()->name().compare( string, Qt::CaseInsensitive ) == 0 )
413  return it.value();
414  }
415 
416  return nullptr;
417 }
418 
419 double QgsLayoutUtils::pointsToMM( const double pointSize )
420 {
421  //conversion to mm based on 1 point = 1/72 inch
422  return ( pointSize * 0.3527 );
423 }
424 
425 double QgsLayoutUtils::mmToPoints( const double mmSize )
426 {
427  //conversion to points based on 1 point = 1/72 inch
428  return ( mmSize / 0.3527 );
429 }
static double snappedAngle(double angle)
Snaps an angle (in degrees) to its closest 45 degree angle.
static double scaleFactorFromItemStyle(const QStyleOptionGraphicsItem *style)
Extracts the scale factor from an item style.
Portrait orientation.
A rectangle specified with double values.
Definition: qgsrectangle.h:40
Base class for all map layer types.
Definition: qgsmaplayer.h:61
void setFlags(QgsRenderContext::Flags flags)
Set combination of flags that will be used for rendering.
Landscape orientation.
static double textWidthMM(const QFont &font, const QString &text)
Calculate a font width in millimeters for a text string, including workarounds for QT font rendering ...
static double relativePosition(double position, double beforeMin, double beforeMax, double afterMin, double afterMax)
Returns a scaled position given a before and after range.
QgsMapSettings mapSettings(const QgsRectangle &extent, QSizeF size, double dpi, bool includeLayerSettings) const
Returns map settings that will be used for drawing of the map.
bool qgsDoubleNear(double a, double b, double epsilon=4 *std::numeric_limits< double >::epsilon())
Compare two doubles (but allow some difference)
Definition: qgis.h:251
QMap< QString, QgsMapLayer * > mapLayers() const
Returns a map of all registered layers by layer ID.
static double fontDescentMM(const QFont &font)
Calculate a font descent in millimeters, including workarounds for QT font rendering issues...
QgsLayoutRenderContext & renderContext()
Returns a reference to the layout&#39;s render context, which stores information relating to the current ...
Definition: qgslayout.cpp:355
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)
Definition: MathUtils.cpp:786
The QgsMapSettings class contains configuration for rendering of the map.
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
QgsRectangle extent() const
Returns the current map extent.
Layout graphical items for displaying a map.
void setScaleFactor(double factor)
Sets the scaling factor for the render to convert painter units to physical sizes.
const QgsLayout * layout() const
Returns the layout the object is attached to.
static QgsRenderContext createRenderContextForMap(QgsLayoutItemMap *map, QPainter *painter, double dpi=-1)
Creates a render context suitable for the specified layout map and painter destination.
QgsRenderContext::Flags renderContextFlags() const
Returns the combination of render context flags matched to the layout context&#39;s settings.
static QgsRenderContext createRenderContextForLayout(QgsLayout *layout, QPainter *painter, double dpi=-1)
Creates a render context suitable for the specified layout and painter destination.
static QFont scaledFontPixelSize(const QFont &font)
Returns a font where size is set in points and the size has been upscaled with FONT_WORKAROUND_SCALE ...
void setPainter(QPainter *p)
Sets the destination QPainter for the render operation.
Reads and writes project states.
Definition: qgsproject.h:85
Base class for layouts, which can contain items such as maps, labels, scalebars, etc.
Definition: qgslayout.h:49
QList< QgsMapLayer * > mapLayersByName(const QString &layerName) const
Retrieve a list of matching registered layers by layer name.
static QgsMapLayer * mapLayerFromString(const QString &string, QgsProject *project)
Resolves a string into a map layer from a given project.
static void rotate(double angle, double &x, double &y)
Rotates a point / vector around the origin.
static void drawText(QPainter *painter, QPointF position, const QString &text, const QFont &font, const QColor &color=QColor())
Draws text on a painter at a specific position, taking care of layout specific issues (calculation to...
static double fontHeightMM(const QFont &font)
Calculate a font height in millimeters, including workarounds for QT font rendering issues...
QgsLayoutItemMap * referenceMap() const
Returns the map item which will be used to generate corresponding world files when the layout is expo...
Definition: qgslayout.cpp:426
Contains information about the context of a rendering operation.
static double fontHeightCharacterMM(const QFont &font, QChar character)
Calculate a font height in millimeters of a single character, including workarounds for QT font rende...
static double fontAscentMM(const QFont &font)
Calculates a font ascent in millimeters, including workarounds for QT font rendering issues...
static QRectF largestRotatedRectWithinBounds(const QRectF &originalRect, const QRectF &boundsRect, double rotation)
Calculates the largest scaled version of originalRect which fits within boundsRect, when it is rotated by the a specified rotation amount.
static QgsRenderContext fromMapSettings(const QgsMapSettings &mapSettings)
create initialized QgsRenderContext instance from given QgsMapSettings
Orientation
Page orientiation.
QgsLayoutMeasurement convertFromLayoutUnits(double length, QgsUnitTypes::LayoutUnit unit) const
Converts a length measurement from the layout&#39;s native units to a specified target unit...
Definition: qgslayout.cpp:340
QgsMapLayer * mapLayer(const QString &layerId) const
Retrieve a pointer to a registered layer by layer ID.
static void relativeResizeRect(QRectF &rectToResize, const QRectF &boundsBefore, const QRectF &boundsAfter)
Resizes a QRectF relative to a resized bounding rectangle.
static double textHeightMM(const QFont &font, const QString &text, double multiLineHeight=1.0)
Calculate a font height in millimeters for a text string, including workarounds for QT font rendering...
static double normalizedAngle(double angle, bool allowNegative=false)
Ensures that an angle (in degrees) is in the range 0 <= angle < 360.
static QgsLayoutItemPage::Orientation decodePaperOrientation(const QString &string, bool &ok)
Decodes a string representing a paper orientation and returns the decoded orientation.
#define M_DEG2RAD