I'm working on an photo app where you can draw lines on an photo.
The background is the photo, and via drawrect I draw lines on a subview.
Every thing works but how can I erase lines on a subview (like an eraser), I tried with clearColor as setStroke.
Is it possible to erase the lines like this.
An implementation of the response given by @omz could be:
(assuming imgBlank
is a UIImageView
placed on top of the main view of the viewcontroller)
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{
UITouch *touch = [touches anyObject];
CGPoint currentPoint = [touch locationInView:self.imgBlank];
NSValue *valCurrPoint=[NSValue valueWithCGPoint:CGPointMake(currentPoint.x, currentPoint.y)];
[self.dots addObject:valCurrPoint];
[self performSelector:@selector(draw:) withObject:valCurrPoint afterDelay:0];
}
-(void)draw:(NSValue*)pointz{
CGPoint point=[pointz CGPointValue];
UIGraphicsBeginImageContextWithOptions(self.imgBlank.frame.size,NO,0);
[self.imgBlank.image drawInRect:CGRectMake(0, 0, self.imgBlank.frame.size.width, self.imgBlank.frame.size.height)];
CGContextSetLineCap(UIGraphicsGetCurrentContext(), kCGLineCapRound);
CGContextSetLineWidth(UIGraphicsGetCurrentContext(),tickness);//set the tickness here
CGContextSetBlendMode(UIGraphicsGetCurrentContext(), kCGBlendModeClear);
CGContextSetRGBStrokeColor(UIGraphicsGetCurrentContext(), 1.0f, 1.0f, 1.0f, 1.0);
CGContextBeginPath(UIGraphicsGetCurrentContext());
CGContextSetShouldAntialias(UIGraphicsGetCurrentContext(), YES);
CGContextMoveToPoint(UIGraphicsGetCurrentContext(), _lastPoint.x, _lastPoint.y);
CGContextAddLineToPoint(UIGraphicsGetCurrentContext(), point.x, point.y);
CGContextStrokePath(UIGraphicsGetCurrentContext());
self.imgBlank.image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
_lastPoint = point;
}
You have to set the blend mode to kCGBlendModeCopy
if you want drawing with a fully transparent color to have any effect.
This is normally done with the CGContextSetBlendMode
function. If you use UIBezierPath
for drawing, you could also use the strokeWithBlendMode:alpha:
method.
I tried using @omz's second suggestion of doing this in UIBezierPath using strokeWithBlendMode:alpha: and it worked great. Here is the code:
if (pen) {
[self updateColorFromPen];
[path setLineWidth:3.0];
} else if (eraser) {
[[UIColor clearColor] setStroke];
[path setLineWidth:42.0];
[path strokeWithBlendMode:kCGBlendModeCopy alpha:1];
}