0

我想擦除在 uiimageview 中的触摸事件中绘制的线条。我想在 touchesEnded 中调用 setNeedsDisplay 但它不起作用。

在 Canvas.m 我有:

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

    UITouch *touch = [touches anyObject];
    self.location = [touch locationInView:self];
}

- (void) touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch *touch = [touches anyObject];
    CGPoint currentLocation = [touch locationInView:self];

    UIGraphicsBeginImageContext(self.frame.size);
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    [self.image drawInRect:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
    CGContextSetLineCap(ctx, kCGLineCapRound);
    CGContextSetLineWidth(ctx, 5.0);
    CGContextSetRGBStrokeColor(ctx, 1.0, 0.0, 0.0, 1.0);
    CGContextBeginPath(ctx);
    CGContextMoveToPoint(ctx, location.x, location.y);
    CGContextAddLineToPoint(ctx, currentLocation.x, currentLocation.y);
    CGContextStrokePath(ctx);
    self.image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    location = currentLocation;
}

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

    [self setNeedsDisplay];
}
4

1 回答 1

1

简单的解决方案 - 在开始时保存原始图像,当您想擦除线条时,只需执行self.image = savedImage

但是,更好的解决方案(具有更好的性能)将是根本不更改图像,而是在图像上具有透明视图并在其中UIImageView绘制。绘图也可以简单得多(例如,使用CGImageRef缓冲区而不是每次都创建图像上下文UIGraphicsBeginImageContext)。

于 2013-04-06T18:02:00.973 回答