问题描述
根据 Path 的文档:
Closed sub-paths enclose a (possibly discontiguous) region of the plane based on the current fillType.
据我所知,这意味着当一个 Path 对象关闭时,它会围绕一个二维区域。
当用户点击屏幕上的一个点时,我想计算用户点击的点与路径包围的区域之间的距离。我知道用户通过 GestureDetector/onPanDown 进行点击,但我无法弄清楚如何计算到路径(或路径包围的区域)的距离。 Path 提供的所有函数似乎都返回 void 或 bool 但没有距离。
想象一下:(红色是我将它绘制到屏幕时的 Path 对象,X 应该是我的用户点击的位置;绿线表示的两者之间的距离是我感兴趣的)
如何计算距离?
解决方法
首先遍历路径的所有点。 并为每个点找出到点击位置的距离并保持最短的距离。
因此要获得路径的点数,请使用 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();
}
从here获得参考