计算点到直线的距离

Fle*_*etL 2 c# geometry

我正在用 C# 编写一个类似绘画的程序。我希望能够在单击靠近一条线时擦除该线(例如,距离 < 10 像素)。我尝试了不同的计算,但最终遇到的问题是,只有当我单击线条的起点或终点附近时,线条才会被删除。介于两者之间的任何事情似乎都不起作用。

令 p 为用户在表单中单击的点,startp 和 endp 为线条的终点。

double a = (endp.Y - startp.Y) / (endp.X - startp.X); // gradient
double b = endp.Y - a * endp.X; // y intercept

// condition such that it only works when i click close to the line segment,
// not the entire infinite line for which the calculation y=ax+b works

double yvalue = p.X * a + b;    // value the line segment has at the x-value which the user clicks on
double alpha = Math.Atan((endp.X - startp.X) / (endp.Y - startp.Y));    
double distance = Math.Sin(alpha) * Math.Abs((yvalue - p.Y));
if (distance<10)
     // remove line
Run Code Online (Sandbox Code Playgroud)

为什么此代码仅适用于靠近起点或终点的点?我确信这不是因为我在示例中省略的条件

小智 5

你要计算的距离可以看成三角形P-startP-endP中P的高度。因此,给出以下公式:

a = dist(startp, endp)
b = dist(startp, p)
c = dist(endp, p)
s = (a + b + c)/2
distance = 2 * sqrt(s(s-a)(s-b)(s-c)) / a
Run Code Online (Sandbox Code Playgroud)

比照。海拔(三角形)