您的位置:首页 > 其它

计算 点到线段(直线)的距离

2013-04-21 00:15 274 查看
方法一:使用向量计算

不叙述原理了,直接看代码

// param : point : 测试点
// pLine : 线段描述类,m_LTPoint、m_RBPoint分别为线段的两点
// return : 点在直线上,true;否则,false
bool HitTestLine(CPoint point, CLineItem *pLine)
{
int dxap = point.x - pLine->m_LTPoint.x; // Vector AP
int dyap = point.y - pLine->m_LTPoint.y;
int dxab = pLine->m_RBPoint.x - pLine->m_LTPoint.x; // Vector AB
int dyab = pLine->m_RBPoint.y - pLine->m_LTPoint.y;

int ab2 = dxab*dxab + dyab*dyab; // Magnitude of AB,AB²

double t; // This will hold the parameter for the Point of projection of P on AB

if (ab2 <= 2)
{
t=0; // A and B coincide
}
else
{
t = (double)(dxap*dxab + dyap*dyab) / ab2; // P的投影点在向量AB上的比例位置,为计算P的投影点准备
}
// Above equation maps to (AP dot normalized(AB)) / magnitude(AP dot normalized(AB))
if (t<0) t = 0; // Projection is beyond A so nearest point is A // 这个判断很重要
if (t>1) t = 1; // Projection is beyond B so nearest point is B

// 求出 点point在直线上的映射点
int xf = pLine->m_LTPoint.x + t * dxab; // Projection point on Seg AB // double->int,提高接下来计算的效率
int yf = pLine->m_LTPoint.y + t * dyab; //

// 点point到映射点的向量
int dxfp = point.x - xf;
int dyfp = point.y - yf;

int nDist2;
nDist2 = dxfp*dxfp + dyfp*dyfp; // 距离的平方
if (nDist2 < 16)
{
return true;
}

return false;
}

方法二:

参考:求点到直线的距离:http://www.cnblogs.com/lauer0246/archive/2009/06/24/1510363.html

求点到直线的距离:http://blog.csdn.net/cay22/article/details/6291462

过点(x1,y1)和点(x2,y2)的直线方程为:KX - Y + (x2y1 - x1y2)/(x2-x1) = 0

设直线斜率为: K = (y2-y1)/(x2-x1), C=(x2y1 - x1y2)/(x2-x1)

点P(x0,y0)到直线 AX + BY +C =0 的距离为:d=|Ax0 + By0 + C|/sqrt(A*A + B*B)

点(x3,y3)到经过点(x1,y1)和点(x2,y2)的直线的最短距离为:

distance = |K*x3 - y3 + C|/sqrt(K*K + 1)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: