2013-03-06 49 views
0

目前我可以检测点是否属于用下面的代码线段:如何检测,如果点位于段

uint8_t point_lies_onSegment(const POINT2D *point, const POINT2D *linea, const POINT2D *lineb) { 
double slope, intercept; 
    double px, py; 
    double left, top, right, bottom; // Bounding Box For Line Segment 
    double dx, dy; 

px = point->x; 
py = point->y; 

dx = lineb->x - linea->x; 
dy = lineb->y - linea->y; 

    slope = dy/dx; 
    // y = mx + c 
    // intercept c = y - mx 
    intercept = linea->y - slope * linea->x; // which is same as y2 - slope * x2 

    // For Bounding Box 
    if(linea->x < lineb->x) { 
    left = linea->x; 
    right = lineb->x; 
    } else { 
    left = lineb->x; 
    right = linea->x; 
    } 
    if(linea->y < lineb->y) { 
    top = linea->y; 
    bottom = lineb->y; 
    } else { 
    top = linea->y; 
    bottom = lineb->y; 
    } 

    //"Equation of the line: %.2f X %c %.2f\n", slope, ((intercept < 0) ? ' ' : '+'), intercept; 

    if(slope * px + intercept > (py - FP_TOLERANCE) && 
    slope * px + intercept < (py + FP_TOLERANCE)) { 
     if(px >= left && px <= right && 
      py >= top && py <= bottom) { 
      return VG_TRUE; 
     } 
     else 
     return VG_FALSE; 
    } 
    else 
    return VG_FALSE; 
} 

但是,如果该行是垂直预期这是行不通的。 例如:

线段=(10,10) - (10,30) 点=(10,20)

此返回FALSE。

如何解决?

回答

1

如果该线是垂直的,则需要检查相关点的x坐标。如果该点的x坐标与垂直线段的x坐标相同,则检查该点的y坐标是否在垂直线段的y坐标之间。

+0

我添加以下代码: \t如果(FP_EQUALS(DX,0.0)){ \t \t如果(PY <= lineb->ý&& PY> = linea-> y)等 \t \t \t返回VG_TRUE; \t \t else \t \t \t return VG_FALSE; \t}它现在有效。谢谢。 – 2013-03-06 02:38:09

2

垂直线将导致您的程序除以零。我很惊讶你会得到任何输出 - 我曾预料它只会崩溃。由于它不会崩溃,因此您可能会将NaN转换为slope,这会导致您的其他问题。例如,您可能想要使用与当前使用的算法不同的算法 - 例如,不要求您计算斜率。

+0

哪种算法不同? – 2013-03-06 01:51:48

+0

卡拉罗在他的回答中暗示了一个,还有很多其他人。我敢肯定,如果你有一点谷歌,你会打开一些东西。 – 2013-03-06 02:02:56

+0

我做了什么卡拉罗建议和工作。谢谢。 – 2013-03-06 02:37:18