使用点阵数在iPhone上绘制多个线/路径

时间:2011-10-22 20:30:28

标签: ios4 drawrect cgcontext

我正在尝试使用CGPoints数组绘制线条来创建绘图视图。

我目前能够绘制多条线但问题是我不知道如何在触摸结束时打破每一条线。

目前的状况是 - 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);
        }
    }
}

请告知: - ))

提前谢谢你,

Dudi Shani-Gabay

1 个答案:

答案 0 :(得分:0)

在这种情况下,我认为最好为不同的行保留单独的数组。让&#34; pointArray&#34;是一个数组,每行绘制数组。

在&#34;触摸开始&#34;方法,您需要将新数组对象添加到pointArray,如下所示:

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

在&#34; touchesMoved&#34;中,您必须替换

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

以下内容:

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

在&#34; drawRect&#34;方法,&#39; for&#39;循环应该是这样的:

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