Calculate distance between the area surrounded by a Path and a specific point in Flutter

1.1k views Asked by At

According to the documentation for Path:

Closed sub-paths enclose a (possibly discontiguous) region of the plane based on the current fillType.

As far as I understand this implies that when a Path object is closed it surrounds a two dimensional area.

When the user clicks on a point of the screen I want to calculate the distance between the point that the user clicks and the area that's surrounded by the path. I get the point that the user clicks via GestureDetector/onPanDown but I have trouble figuring out how to calculate the distance to the path (or the area surrounded by the path). All the functions that Path offers seem to return void or bool but no distances.

Imagine for illustration: (red is the Path object when I draw it to the screen and the X is supposed to be where my user clicks; the distance between the two represented by the green line is what I'm interested in) enter image description here

How do I calculate the distance?

1

There are 1 answers

2
Ravi Sevta On BEST ANSWER

First of all traverse through all points of the path. and for each point find out the distance to clicked position and hold the shortest one.

So to get the points of the path use PathMetrics.

double getShortestDistance(Path path, Offset clickedPoint) {
    PathMetrics pathMetrics = path.computeMetrics();
    
    double minDistance;
    
    pathMetrics.toList().forEach((element) {
      for (var i = 0; i < element.length; i++) {
        Tangent tangent = element.getTangentForOffset(i.toDouble());
        Offset pos = tangent.position;
        
        double distance = getDistance(pos,clickedPoint);
        if(minDistance==null||distance<minDistance) {
          minDistance = distance;
        }
      }
    });

    return minDistance;
  }

  double getDistance(Offset pos, Offset clickedPoint) {
    double dx = pos.dx-clickedPoint.dx;
    double dy = pos.dy-clickedPoint.dy;
    double distance = sqrt(dx*dx+dy*dy);
    return distance.abs();
  }

got reference from here