Kir*_*rst 5 wpf geometry line wpf-controls polyline
我有一个点和一条路径、折线或一组点来创建直线。
如何找到路径上最接近另一个断开点的点?
与任何 WPF 几何控件一样,可以轻松存储或传输路径/折线,但这些控件是否带有GetDistanceFrom类型方法?有什么简单的方法可以实现这个目标吗?
这是我作为解决方案实现的算法。如果你花了十多分钟思考的话,这里没有什么是“不明显的”。
我将参考您可以在这里找到的距离算法:/sf/answers/105120781/
上面链接的答案使用投影来测试该点是否比任何其他点更接近间隔的任一端。我已经修改了该答案中的函数以返回该投影上的点的位置。请注意,如果您还没有阅读链接的答案,这个答案可能没有任何意义!
private Point GetClosestPointOnLine(Point start, Point end, Point p)
{
var length = (start - end).LengthSquared;
if (length == 0.0)
return start;
// Consider the line extending the segment, parameterized as v + t (w - v).
// We find projection of point p onto the line.
// It falls where t = [(p-v) . (w-v)] / |w-v|^2
var t = (p - start) * (end - start) / length;
if (t < 0.0)
return start; // Beyond the 'v' end of the segment
else if (t > 1.0)
return end; // Beyond the 'w' end of the segment
// Projection falls on the segment
var projection = start + t * (end - start);
return projection;
}
Run Code Online (Sandbox Code Playgroud)