检查线段与点之间的距离

Luk*_*man 10 algorithm geometry objective-c

我有两个点A和B在设备屏幕上定义一个线段加上另一个点C.使用易于编码的高效和短算法(最好使用标准数学库),如何检查线段AB是否在与C的距离R?

我知道有一种简单的方法可以找到从点到线的最短距离,但它假设线条无限长.我所拥有的是具有两个端点的线段.

我考虑在Math SE中发布这个但是决定不这样做,因为我不想把所有这些长数学公式作为答案,如https://math.stackexchange.com/questions/2837/how-to-tell-if -a-line-segment-with-a-circle.我需要的是一个高效可读的计算机算法,而不是一个正式的数学定理.

p/s:我有以下需要实现的Objective-C方法框架:

typedef struct {
  CGPoint a;
  CGPoint b;
} CGLineSegment;

+ (BOOL)isLineSegment:(CGLineSegment)line withinRadius:(CGFloat)radius fromPoint:(CGPoint)point {

}
Run Code Online (Sandbox Code Playgroud)

编辑解决方案:

感谢veredesmarald的回答(我已经接受了)我已经实现了这个方法,在这里作为其他人的参考:

+ (BOOL)isLineSegment:(CGLineSegment)line withinRadius:(CGFloat)radius fromPoint:(CGPoint)point {
    CGPoint v = CGPointMake(line.b.x - line.a.x, line.b.y - line.a.y);
    CGPoint w = CGPointMake(point.x - line.a.x, point.y - line.a.y);
    CGFloat c1 = dotProduct(w, v);
    CGFloat c2 = dotProduct(v, v);
    CGFloat d;
    if (c1 <= 0) {
        d = distance(point, line.a);
    }
    else if (c2 <= c1) {
        d = distance(point, line.b);
    }
    else {
        CGFloat b = c1 / c2;
        CGPoint Pb = CGPointMake(line.a.x + b * v.x, line.a.y + b * v.y);
        d = distance(point, Pb);
    }
    return d <= radius;
}

CGFloat distance(const CGPoint p1, const CGPoint p2) {
    return sqrt(pow(p2.x - p1.x, 2) + pow(p2.y - p1.y, 2));
}

CGFloat dotProduct(const CGPoint p1, const CGPoint p2) {
    return p1.x * p2.x + p1.y * p2.y;
}
Run Code Online (Sandbox Code Playgroud)

ver*_*ald 7

当我必须实现一种方法来确定从点到图形分配的间隔的距离时,我发现这个页面非常有用:关于点到线的点和距离

特别是,您应该关注点到光线或线段的距离.

文章中的伪代码(其中·是点积,d()是两点之间的距离):

distance( Point P, Segment P0:P1 )
{
      v = P1 - P0
      w = P - P0
      if ( (c1 = w·v) <= 0 )
            return d(P, P0)
      if ( (c2 = v·v) <= c1 )
            return d(P, P1)
      b = c1 / c2
      Pb = P0 + bv
      return d(P, Pb)
}
Run Code Online (Sandbox Code Playgroud)

该方法依赖于点积来确定垂线的底边是否在该间隔内,如果不是哪个终点更近.