2011-10-22 47 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); 
    } 
} 
相关问题