Skip to content
Permalink
Browse files

Add method to calculate total length of a QPolygonF line

  • Loading branch information
nyalldawson committed Mar 18, 2021
1 parent cfde40d commit 99c5ac3d66cc3613fa9e070a891d6cc8d60e700e
@@ -732,6 +732,13 @@ Calculate a point on the surface of a QPolygonF
static bool pointInPolygon( const QPolygonF &points, QPointF point );
%Docstring
Calculate whether a point is within of a QPolygonF
%End

static double polylineLength( const QPolygonF &polyline );
%Docstring
Returns the total length of a ``polyline``.

.. versionadded:: 3.20
%End

static QPolygonF polylineSubstring( const QPolygonF &polyline, double startOffset, double endOffset );
@@ -4189,6 +4189,24 @@ bool QgsSymbolLayerUtils::pointInPolygon( const QPolygonF &points, QPointF point
return inside;
}

double QgsSymbolLayerUtils::polylineLength( const QPolygonF &polyline )
{
if ( polyline.size() < 2 )
return 0;

double totalLength = 0;
auto it = polyline.begin();
QPointF p1 = *it++;
for ( ; it != polyline.end(); ++it )
{
QPointF p2 = *it;
const double segmentLength = std::sqrt( std::pow( p1.x() - p2.x(), 2.0 ) + std::pow( p1.y() - p2.y(), 2.0 ) );
totalLength += segmentLength;
p1 = p2;
}
return totalLength;
}

QPolygonF QgsSymbolLayerUtils::polylineSubstring( const QPolygonF &polyline, double startOffset, double endOffset )
{
if ( polyline.size() < 2 )
@@ -657,6 +657,13 @@ class CORE_EXPORT QgsSymbolLayerUtils
//! Calculate whether a point is within of a QPolygonF
static bool pointInPolygon( const QPolygonF &points, QPointF point );

/**
* Returns the total length of a \a polyline.
*
* \since QGIS 3.20
*/
static double polylineLength( const QPolygonF &polyline );

/**
* Returns the substring of a \a polyline which starts at \a startOffset from the beginning of the line
* and ends at \a endOffset from the start of the line.
@@ -270,6 +270,17 @@ def testDecodeSldUom(self):
decode = QgsSymbolLayerUtils.decodeSldUom("http://www.opengeospatial.org/se/units/pixel")
self.assertEqual(decode, (QgsUnitTypes.RenderPixels, 1.0))

def testPolylineLength(self):
"""
Test QgsSymbolLayerUtils.polylineLength
"""
self.assertEqual(QgsSymbolLayerUtils.polylineLength(QPolygonF()), 0.0)
self.assertEqual(
QgsSymbolLayerUtils.polylineLength(QPolygonF([QPointF(11, 12), QPointF(11, 12)])), 0.0)
self.assertEqual(
QgsSymbolLayerUtils.polylineLength(QPolygonF([QPointF(11, 2), QPointF(11, 12), QPointF(11, 12)])), 10.0)
self.assertEqual(QgsSymbolLayerUtils.polylineLength(QPolygonF([QPointF(11, 2), QPointF(11, 12), QPointF(111, 12)])), 110.0)

def testPolylineSubstring(self):
res = QgsSymbolLayerUtils.polylineSubstring(QPolygonF(), 1, 2) # no crash
self.assertFalse(res)

0 comments on commit 99c5ac3

Please sign in to comment.