我想在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];
}
答案 0 :(得分:1)
简单的解决方案 - 在开始时保存原始图像,当您想要删除线条时,只需执行self.image = savedImage
然而,更好的解决方案(具有更好的性能)将是根本不改变图像,而是在UIImageView
上具有透明视图并在其中绘制。绘图也可以更简单(例如,使用CGImageRef
缓冲区而不是每次UIGraphicsBeginImageContext
创建图像上下文。)