2012-10-16 32 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