2012-10-16 31 views
1

请参阅图片。我怎样才能得到两条线的交点(即绿色圆点)?我想剪裁图像的内部部分。关闭路径是行中的任何地方。如何在iPhone SDK中找到闭合路径(双线交叉点)?

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

此代码用于绘制线条。线条图工作正常,裁剪也工作正常......但交叉点是我的主要问题。请帮帮我。

enter image description here

+0

喜摩尼已经找到了这个问题的解决方案,如果ü好心做帮我解决这个问题 – hari

回答

2

理念,检查是否与FIRSTLINE <> lastLine所,FIRSTLINE <> secondlastline ... FIRSTLINE <> thirdline =>二线<> lastLine所等,这应该给你最外面的路口开始交叉。

下面的代码没有经过测试,但应该帮助您解决您的问题。

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

谢谢乔纳森Cichon ......我将与此尝试。 – Mani

+0

尼斯计算中的+1 :) – 2013-02-16 06:18:42

+0

以下部分是做什么的? int d =(x1-x2)*(y3-y4) - (y1-y2)*(x3-x4); if(d == 0)return CGPointNULL; (x3-x4)*(x1 * y2-y1 * x2) - (x1-x2)*(x3 * y4-y3 * x4))/ d;(x3-y4-y2) (y3-y4)*(x1 * y2-y1 * x2) - (y1-y2)*(x3 * y4-y3 * x4))/ d; 它计算距离吗?我在哪里可以找到更多关于它的信息? – Pablo