简体   繁体   中英

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

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) 在此处输入图像描述

How do I calculate the distance?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM