日期:2014-05-19  浏览次数:20952 次

求一个好的算法!
很简单,求平面上一点,到这个平面的一条线段的距离,注意是线段不是直线。

------解决方案--------------------
你在搞几何吗?先帮你顶一下在说
------解决方案--------------------
private double PointToLine( // 计算点到线段的距离
Point APoint, // 点的坐标
Point ALineA, Point ALineB // 线段的坐标
) // 返回点到直线的距离
{
if (ALineA.X == ALineB.X && ALineA.Y == ALineB.Y)
return 0;
double T = ((double)(ALineA.X - ALineB.X) * (ALineA.X - APoint.X) +
(ALineA.Y - ALineB.Y) * (ALineA.Y - APoint.Y)) /
((ALineA.X - ALineB.X) * (ALineA.X - ALineB.X) +
(ALineA.Y - ALineB.Y) * (ALineA.Y - ALineB.Y));
if (T > 1)
T = 1.0;
else if (T < 0)
T = 0.0;
double X = ALineA.X + T * (ALineB.X - ALineA.X);
double Y = ALineA.Y + T * (ALineB.Y - ALineA.Y);
return Math.Sqrt((X - APoint.X) * (X - APoint.X) +
(Y - APoint.Y) * (Y - APoint.Y));
}

private void Form1_MouseMove(object sender, MouseEventArgs e)
{
Point vLineA = new Point(30, 30);
Point vLineB = new Point(45, 75);
using (Graphics vGraphics = CreateGraphics())
{
vGraphics.DrawLine(Pens.Black, vLineA, vLineB);
}
Text = PointToLine(e.Location, vLineA, vLineB).ToString();
}

//原理就不说了,测试效果吧