求点在线上的投影点
public enum PointPositonType
{
OutOfStartPoint,
InTheLine,
OutOfEndPoint
}
public static PointPositonType GetNearestPoint(Point startPoint, Point endPoint, Point outPoint, out Point nearestPoint)
{
nearestPoint = new Point();
if (Math.Abs(endPoint.Y - startPoint.Y)
{
nearestPoint.X = outPoint.X;
nearestPoint.Y = startPoint.Y;
}
else //垂直向量斜率之积为-1
{
double dIntercept1 = (endPoint.Y - startPoint.Y) / (endPoint.X - startPoint.X);
double dIntercept2 = -1.0 / dIntercept1;
nearestPoint.X = (dIntercept1 * startPoint.X - dIntercept2 * outPoint.X + outPoint.Y - startPoint.Y) / (dIntercept1 - dIntercept2);
nearestPoint.Y = dIntercept1 * (nearestPoint.X - startPoint.X) + startPoint.Y;
}
Vector ab = endPoint - startPoint;
Vector ac = outPoint - startPoint;
//c在ab线段左侧延长线上,c与ab线段所成的角为钝角
double f = ab * ac;
if (f
{
return PointPositonType.OutOfStartPoint;
}
//c在ab线段的右侧延长线上,c与ab线段所成的角为锐角
double d = ab * ab;
if (f > d)
{
return PointPositonType.OutOfEndPoint;
}
// c在ab线段上的投影点
return PointPositonType.InTheLine;
}
推导公式 为: