点到直线的距离可以直接做垂线求取,但线段是有首尾点的,若要求距离则要考虑首尾点。

  点和线段的关系大致可以有下面几种

 

  1. double GetPointDistance(CPoint p1, CPoint p2)   
  2. {  
  3.  return sqrt((p1.x-p2.x)*(p1.x-p2.x)+(p1.y-p2.y)*(p1.y-p2.y));  
  4. }  
  5. float GetNearestDistance(CPoint PA, CPoint PB, CPoint P3)  
  6. {  
  7.   
  8. //----------2--------------------   
  9.  float a,b,c;  
  10.  a=GetPointDistance(PB,P3);  
  11.  if(a<=0.00001)  
  12.   return 0.0f;  
  13.  b=GetPointDistance(PA,P3);  
  14.  if(b<=0.00001)  
  15.   return 0.0f;  
  16.  c=GetPointDistance(PA,PB);  
  17.  if(c<=0.00001)  
  18.   return a;//如果PAPB坐标相同,则退出函数,并返回距离   
  19. //------------------------------   
  20.    
  21.  if(a*a>=b*b+c*c)//--------3--------   
  22.   return b;      //如果是钝角返回b   
  23.  if(b*b>=a*a+c*c)//--------4-------   
  24.   return a;      //如果是钝角返回a   
  25.    
  26. //1   
  27.  float l=(a+b+c)/2;     //周长的一半   
  28.  float s=sqrt(l*(l-a)*(l-b)*(l-c));  //海伦公式求面积,也可以用矢量求   
  29.  return 2*s/c;  
  30. }    
posted on 2013-12-26 09:35  知识天地  阅读(1204)  评论(0编辑  收藏  举报