2011-10-22 88 views
2

我試圖通過使用CGPoint數組繪製線來創建繪圖視圖。使用陣列點在iPhone上繪製多條線/路徑

我目前能夠繪製多條線,但問題是我不知道如何在觸摸結束時斷開每條線。

當前狀態爲 - line1被繪製直到被碰撞 當再次觸摸時,line2也被繪製,但是,line1端點連接了line2的起點。

執行標準如下:

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event 
{ 
    NSUInteger tapCount = [[touches anyObject] tapCount]; 
    if (tapCount == 2) 
    { 
     [pointArray removeAllObjects]; 
     [self setNeedsDisplay]; 
    } 
    else 
    { 
     if ([pointArray count] == 0) 
      pointArray = [[NSMutableArray alloc] init]; 
     UITouch *touch = [touches anyObject]; 
     start_location = [touch locationInView:self]; 
     [pointArray addObject:[NSValue valueWithCGPoint:start_location]]; 
    } 
} 
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event 
{ 
    UITouch *touch = [touches anyObject]; 
    current_location = [touch locationInView:self]; 
    [pointArray addObject:[NSValue valueWithCGPoint:current_location]]; 
    [self setNeedsDisplay];  
} 

-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event 
{ 

} 



-(void)drawRect:(CGRect)rect 
{ 
    if ([pointArray count] > 0) 
    { 
     int i; 
     CGContextRef context = UIGraphicsGetCurrentContext(); 
     CGContextSetLineWidth(context, 2.0); 
     CGContextSetStrokeColorWithColor(context, [UIColor blueColor].CGColor); 
     for (i=0; i < ([pointArray count] -1); i++) 
     { 
      CGPoint p1 = [[pointArray objectAtIndex:i]CGPointValue]; 
      CGPoint p2 = [[pointArray objectAtIndex:i+1]CGPointValue]; 
      CGContextMoveToPoint(context, p1.x, p1.y); 
      CGContextAddLineToPoint(context, p2.x, p2.y); 
      CGContextStrokePath(context); 
     } 
    } 
} 

請指教:-))

謝謝你在前進,

杜迪·沙尼 - 加貝

回答

0

在這種情況下,我認爲其更好爲你保留單獨的行單獨的數組。讓「pointArray」是一個數組,其中每行繪製的數組數量。

在 「的touchesBegan」 的方法,你需要新的數組對象添加到pointArray如下:

start_location = [touch locationInView:self]; 
NSMutableArray *newLineArray = [[NSMutableArray alloc] init]; 
[pointArray addObject:newLineArray]; 
[[pointArray lastObject] addObject:[NSValue valueWithCGPoint:start_location]]; 

在 「touchesMoved」,你有以下取代

[pointArray addObject:[NSValue valueWithCGPoint:current_location]]; 

[[pointArray lastObject] addObject:[NSValue valueWithCGPoint:current_location]]; 

在「drawRect」方法中,'for'循環應該是這樣的:

for (i=0; i < [pointArray count]; i++) 
{ 
    for (int j=0; j < ([[pointArray objectAtIndex:i] count] -1); j++) 
    { 
     CGPoint p1 = [[[pointArray objectAtIndex:i] objectAtIndex:j]CGPointValue]; 
     CGPoint p2 = [[[pointArray objectAtIndex:i] objectAtIndex:j+1]CGPointValue]; 
     CGContextMoveToPoint(context, p1.x, p1.y); 
     CGContextAddLineToPoint(context, p2.x, p2.y); 
     CGContextStrokePath(context); 
    } 
} 
相關問題