且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在iPhone SDK中找到结束路径(两行交叉点)?

更新时间:2022-06-20 23:45:20

想法,检查以第一行开头的交叉点<> lastline,firstline<> secondlastline ... firstline<> thirdline => secondline<> lastline etc这应该给你最外面的交叉点。

Idea, check for intersections beginning with firstline<>lastline, firstline<>secondlastline ... firstline<>thirdline => secondline<>lastline etc. This should give you the outer most intersection.

以下代码没有经过测试,但可以帮助解决你的问题。

The following Code is not tested, but should help you with your problem.

typedef struct {
    CGPoint startPoint;
    CGPoint endPoint;
} Line;

#define CGPointNULL CGPointMake(NAN, NAN)

#define Line(_i_) {CGPointFromString(touchPoints[_i_-1]), CGPointFromString(touchPoints[_i_])};

CGPoint LineIntersects(Line *first, Line *second) {
    int x1 = first->startPoint.x; int y1 = first->startPoint.y;
    int x2 = first->endPoint.x; int y2 = first->endPoint.y;

    int x3 = second->startPoint.x; int y3 = second->startPoint.y;
    int x4 = second->endPoint.x; int y4 = second->endPoint.y;

    int d = (x1-x2)*(y3-y4) - (y1-y2)*(x3-x4);

    if (d == 0) return CGPointNULL;

    int xi = ((x3-x4)*(x1*y2-y1*x2)-(x1-x2)*(x3*y4-y3*x4))/d;
    int yi = ((y3-y4)*(x1*y2-y1*x2)-(y1-y2)*(x3*y4-y3*x4))/d;

    return CGPointMake(xi,yi);
}

static inline BOOL CGPointIsValid(CGPoint p) {
    return (p.x != NAN && p.y != NAN);
}

- (CGPoint)mostOuterIntersection:(NSArray *)touchPoints {
    CGPoint intersection = CGPointNULL;
    int touchCount = [touchPoints count];

    for(int i = 1; i<touchCount; i++) {
        Line first = Line(i);
        for(int j = touchCount-1; j>i+1; j--) {
            Line last = Line(j);
            intersection = LineIntersects(&first, &last);
            if(CGPointIsValid(intersection)) {
                break;
            }
        }
    }
    return intersection;
}