如何在一条曲线上,获取到距离指定点最近的点位置?
与上一篇 C# 曲线上的点(一) 获取指定横坐标对应的纵坐标值 类似,
我们通过曲线上获取的密集点,通过俩点之间连线,获取连线上最近的点。我们能够获取到一系列最近的点集,最近只取距离最小的点即可。
我们这样的算法是否精确呢?不算太精确,但是对于获取曲线上最近点,基本能满足。
斜率变化不大的线段,点不密集;斜率变化较大的线段,点相当密集,所以由此点集得到的最近点,是相对准确的。
实现方案,以下代码可以直接复用:
public static Point GetClosestPointOnPath(Point p, Geometry geometry)
{
PathGeometry pathGeometry = geometry.GetFlattenedPathGeometry(); var points = pathGeometry.Figures.Select(f => GetClosestPointOnPathFigure(f, p))
.OrderBy(t => t.Item2).FirstOrDefault();
return points?.Item1 ?? new Point(, );
} private static Tuple<Point, double> GetClosestPointOnPathFigure(PathFigure figure, Point p)
{
List<Tuple<Point, double>> closePoints = new List<Tuple<Point, double>>();
Point current = figure.StartPoint;
foreach (PathSegment s in figure.Segments)
{
PolyLineSegment segment = s as PolyLineSegment;
LineSegment line = s as LineSegment;
Point[] points;
if (segment != null)
{
points = segment.Points.ToArray();
}
else if (line != null)
{
points = new[] { line.Point };
}
else
{
throw new InvalidOperationException();
}
foreach (Point next in points)
{
Point closestPoint = GetClosestPointOnLine(current, next, p);
double d = (closestPoint - p).LengthSquared;
closePoints.Add(new Tuple<Point, double>(closestPoint, d));
current = next;
}
}
return closePoints.OrderBy(t => t.Item2).First();
}
俩点之间的连线,如果当前点在此方向的投影为负或者大于当前长度,则取俩侧的点:
private static Point GetClosestPointOnLine(Point start, Point end, Point p)
{
double length = (start - end).LengthSquared;
if (Math.Abs(length) < 0.01)
{
return start;
}
Vector v = end - start;
double param = (p - start) * v / length;
return (param < 0.0) ? start : (param > 1.0) ? end : (start + param * v);
}
效果图: