当前,我可以使用以下代码检测该点是否属于线段:

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)
这个返回错误。
如何解决?

最佳答案

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

10-06 16:02
查看更多