How to find the closing path(two line intersection) in iPhone SDK?

杀马特。学长 韩版系。学妹 提交于 2019-12-06 09:12:00

问题


Please see the image. How can I get the two line intersection point(that is green rounded point)? I want to crop the inner part of the image. The closing path is any where in the line.

context = UIGraphicsGetCurrentContext();
CGContextBeginPath(context);
CGContextSetLineWidth(context, 1.0 * self.scale);
CGContextSetLineCap(context, kCGLineCapRound);
[[UIColor redColor] setStroke];

CGPoint firstPoint = CGPointFromString([self.touchPoints objectAtIndex:0]);
CGContextMoveToPoint(context, firstPoint.x, firstPoint.y);

for (NSString *pointString in self.touchPoints) {
    CGPoint point = CGPointFromString(pointString);
    CGContextAddLineToPoint(context, point.x, point.y);
}

CGContextStrokePath(context);

This code used for the draw the lines. Line drawing is working fine, cropping also working fine...But the intersection point is my major problem. Please help me.


回答1:


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;
}


来源:https://stackoverflow.com/questions/12909008/how-to-find-the-closing-pathtwo-line-intersection-in-iphone-sdk

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!