I want to know the length of a Path
.
For example, if I have a straight line I can just compute the length with its start x
,y
and end x
,y
values. But it gets quickly very tricky if I use QuadCurves
or CubicCurves
.
Is there any way to get the length or an approximation of the length of a Path
?
For example the following path:
Path path = new Path();
MoveTo moveTo = new MoveTo(start.getX(), start.getY());
double controlPointX = 50;
CubicCurveTo cubicCurveTo = new CubicCurveTo(start.getX() + controlPointX, start.getY(),
start.getX() + controlPointX, end.getY(), end.getX(), end.getY());
path.getElements().addAll(moveTo, cubicCurveTo);
I needed this recently as well. I couldn't find any solutions online, but it occurred to me
PathTransition
must be calculating it. It does, seePathTransition.recomputeSegment
, wheretotalLength
is calculated.Unfortunately, it uses many internal APIs in
Node
and thePathElement
to convert thePath
to ajava.awt.geom.Path2D
. I extracted these methods out and replaced other usages ofcom.sun
classes withjava.awt
ones, then pulled the parts relevant to calculating length out ofPathTransition.recomputeSegments
.The resulting code is below. It is in Kotlin not Java, but it should be easy to convert it back to Java. I have not yet tested it extensively but it seems to be working on the fairly complex paths I have tested it against. I've compared my results to the length calculated by
PathTransition
and they are very close, I believe the discrepancies are due to my code usingPath2D.Double
where asPath2D.Float
is used byPathElement.impl_addTo
.