如何擦除iphone中的线条画(CGGraphics)?

时间:2012-01-25 06:08:18

标签: iphone drawing line cgcontextdrawimage

我正在制作一个iPhone应用程序的绘图,用户可以画一条线也可以删除所以任何身体可以帮我如何删除线条或绘图?

抽奖代码

- (void)drawRect:(CGRect)rect {

    float newHeight;
    float newWidth;

    if (!myDrawing) {
        myDrawing = [[NSMutableArray alloc] initWithCapacity:0];
    }
    CGContextRef ctx = UIGraphicsGetCurrentContext();

    if (myPic != NULL) {
        float ratio = myPic.size.height/460;
        if (myPic.size.width/320 > ratio) {
            ratio = myPic.size.width/320;
        }

        newHeight = myPic.size.height/ratio;
        newWidth = myPic.size.width/ratio;

        [myPic drawInRect:CGRectMake(0,0,newWidth,newHeight)];
    }
    if ([myDrawing count] > 0) {
        CGContextSetLineWidth(ctx, 5);

        for (int i = 0 ; i < [myDrawing count] ; i++) {
            NSArray *thisArray = [myDrawing objectAtIndex:i];

            if ([thisArray count] > 2) {
                float thisX = [[thisArray objectAtIndex:0] floatValue];
                float thisY = [[thisArray objectAtIndex:1] floatValue];

                CGContextBeginPath(ctx);
                CGContextMoveToPoint(ctx, thisX, thisY);

                for (int j = 2; j < [thisArray count] ; j+=2) {
                    thisX = [[thisArray objectAtIndex:j] floatValue];
                    thisY = [[thisArray objectAtIndex:j+1] floatValue];

                    CGContextAddLineToPoint(ctx, thisX,thisY);
                }
                CGContextStrokePath(ctx);
            }
        }
    }
}

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

    [myDrawing addObject:[[NSMutableArray alloc] initWithCapacity:4]];

    CGPoint curPoint = [[touches anyObject] locationInView:self];
    [[myDrawing lastObject] addObject:[NSNumber numberWithFloat:curPoint.x]];
    [[myDrawing lastObject] addObject:[NSNumber numberWithFloat:curPoint.y]];
}

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

    CGPoint curPoint = [[touches anyObject] locationInView:self];
    [[myDrawing lastObject] addObject:[NSNumber numberWithFloat:curPoint.x]];
    [[myDrawing lastObject] addObject:[NSNumber numberWithFloat:curPoint.y]];

    [self setNeedsDisplay];
}

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

    CGPoint curPoint = [[touches anyObject] locationInView:self];
    [[myDrawing lastObject] addObject:[NSNumber numberWithFloat:curPoint.x]];
    [[myDrawing lastObject] addObject:[NSNumber numberWithFloat:curPoint.y]];

    [self setNeedsDisplay];

}

-(void)cancelDrawing {

    [myDrawing removeAllObjects];
    [self setNeedsDisplay];

}

1 个答案:

答案 0 :(得分:3)

您可以使用CGContextSetStrokeColorWithColor并在绘制线条时设置视图背景的颜色,使其看起来像是在擦除线条。

如果您想在绘图时提供用户撤消功能,那么可以为此创建以下功能,

-(void)undoDrawing {

    [myDrawing removeLastObject];
    [self setNeedsDisplay];

}

希望这会有所帮助......