Search code examples
flutterpathmetrics

Get length of path of an arc in flutter


I am currently working on a Flutter project and I was trying to understand how computeMetrics() work.

Android

I previously implemented an Android solution to work with arcs, and it works. Part of the implementation is shown below:

   final RectF oval = new RectF(centerX - radiusArc, centerY - radiusArc, centerX + radiusArc, centerY + radiusArc);
    mPath.addArc(oval, startAngle, sweepAngle);

    PathMeasure pm = new PathMeasure(mPath, false);
    float[] xyCoordinate = {startPoint.x, startPoint.y};
    float pathLength = pm.getLength();

Flutter

and now I was trying to replicate the same in Flutter (.dart). For this reason, I am using the following implementation

  final Rect oval = Rect.fromLTRB(centerX - radiusArc, centerY - radiusArc, centerX + radiusArc, centerY + radiusArc);
  mPath.addArc(oval, startAngle, sweepAngle);

  List<num> xyCoordinate = new List<num>(2);
  xyCoordinate[0] = startPoint.x;
  xyCoordinate[1] = startPoint.y;

  List<PathMetric> pm = mPath.computeMetrics().toList();
  double pathLength = pm.iterator.current.length;

I have tried to follow a couple of examples to understand how could be possible to get the length of the path, but when using my implementation, pm.iterator.current is null and therefore I am unable to get the length

I assume that I have understood wrongly how computeMetrics() works.


Solution

  • I think you need to iterate over the List and add length of each PathMetric to get the path length.

    double pathLength = 0;
    pm.forEach((contour){
      pathLength += contour.length;
    });
    print(pathLength);
    

    This is because, like the documentation of computeMetrics() explains -

    A Path is made up of zero or more contours.

    A PathMetric object describes properties of an individual contour, such as its length etc.

    Further, what computeMetrics() returns is an iterable collection of individual PathMetrics each corresponding to the individual contours that make up the Path. So in order to get the length of the Path, we need to add up the lengths of each PathMetric (contour) in the list, which is List<PathMetric> pm = mPath.computeMetrics().toList();