clear the drawing on UIImage?

1.1k Views Asked by At

I draw in a portion of UIButtons image, after clicking clear option I need to reset the buttons image to first one(remove the drawing). I set the image of UIButton with setImage property, but it was not working, How to clear the drawing from image? I use the following code to draw on UIImage,

    UIImageView *imgView =[[UIImageView alloc]init];      
    UIGraphicsBeginImageContext(self.frame.size);
    [imgView.image drawInRect:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
    CGContextSetLineCap(UIGraphicsGetCurrentContext(), kCGLineCapRound);
    CGContextSetLineWidth(UIGraphicsGetCurrentContext(), self.drawingWidth);


    CGContextSetStrokeColorWithColor(UIGraphicsGetCurrentContext(),lipColor.CGColor);
    CGContextSetAlpha(UIGraphicsGetCurrentContext(), self.currntAlpha);
    CGContextBeginPath(UIGraphicsGetCurrentContext());
    CGContextMoveToPoint(UIGraphicsGetCurrentContext(), lastPoint.x, lastPoint.y);
    CGContextAddLineToPoint(UIGraphicsGetCurrentContext(), currentPoint.x, currentPoint.y);
    CGContextStrokePath(UIGraphicsGetCurrentContext());
    CGContextFlush(UIGraphicsGetCurrentContext());
    CGContextSetBlendMode(UIGraphicsGetCurrentContext(), kCGBlendModeOverlay);
    imgView.image = UIGraphicsGetImageFromCurrentImageContext();
    imgView.frame=CGRectMake(0, 0, self.frame.size.width, self.frame.size.height);// Set frame for imageView
    [self.imageView addSubview:imgView];
    UIGraphicsEndImageContext();
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextClearRect(context, self.bounds);
    imgView.layer.shadowOffset = CGSizeZero;
    imgView.layer.masksToBounds = NO;        
    imgView.alpha=0.05;
    lastPoint=currentPoint;
    self.layer.shadowOpacity=0.01;

Any help is much appreciated!!!!!!

1

There are 1 best solutions below

0
Jay Gajjar On

Simple solution - save the original image at the beginning and when you want to erase the lines just do:

self.image = savedImage

However, much better solution (with better performance) would be to not changing the image at all but having a transparent view over the UIImageView and draw inside it. The drawing could also be much simpler (e.g. having a CGImageRef buffer instead of creating an image context everytime by UIGraphicsBeginImageContext).