How to erase image by using touch in objective-c i

2019-06-13 16:26发布

问题:

I am working on a project where I have added a UIImage above another Image. Now, I have to erase some part or whole of that top image by using smooth touch. I have seen many other questions which are quite similar to mine. But they are not properly answered or might not worked in my case.

Please suggest me some sample code or any tutorial for this.

Thanks in advance

回答1:

create image view.....

- (void)viewDidLoad
{
    eraseimg1 = [[UIImageView alloc] initWithFrame:CGRectMake(20,100, 80, 80)];
    eraseimg1.image = [UIImage imageNamed:@"qute.jpg"];
    [self.view  addSubview:eraseimg1];
    eraseimg1.userInteractionEnabled = YES;
    [super viewDidLoad];
}

touchesMoved: event to fingar move to erase the image.

-(void)touchesMoved:(NSSet*)touches withEvent:(UIEvent*)event
{
    UITouch *touch = [[event allTouches] anyObject];
    UIGraphicsBeginImageContext(eraseimg1.frame.size);
    [eraseimg1.image drawInRect:CGRectMake(0, 0,eraseimg1.frame.size.width, eraseimg1.frame.size.height)];
    CGContextSetBlendMode(UIGraphicsGetCurrentContext( ),kCGBlendModeClear);
    CGContextSetLineCap(UIGraphicsGetCurrentContext(), kCGLineCapRound);
    CGContextSetLineWidth(UIGraphicsGetCurrentContext( ), 50);
    CGContextSetStrokeColorWithColor(UIGraphicsGetCurrentContext(), [[UIColor clearColor] CGColor]);
    CGContextBeginPath(UIGraphicsGetCurrentContext());
    CGContextMoveToPoint(UIGraphicsGetCurrentContext(), lastTouch1.x, lastTouch1.y);
    CGContextAddLineToPoint(UIGraphicsGetCurrentContext(), lastTouch1.x, lastTouch1.y);
    CGContextAddRect(UIGraphicsGetCurrentContext(),CGRectMake(0,0,80,20));
    CGContextStrokePath(UIGraphicsGetCurrentContext()) ;
    eraseimg1.image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
}