How to erase some portion of a UIImageView's image on iOS?

后端 未结 2 1416
不知归路
不知归路 2020-12-08 18:04

I have a view with UIImageView and an image set to it. I want to erase the image as something like we do in photoshop with an eraser. How do I achieve this? Also, how do I u

相关标签:
2条回答
  • 2020-12-08 18:25
    UIGraphicsBeginImageContext(imgBlankView.frame.size);
    [imgBlankView.image drawInRect:CGRectMake(0, 0, imgBlankView.frame.size.width, imgBlankView.frame.size.height)];
    
    CGContextSetLineCap(UIGraphicsGetCurrentContext(), kCGLineCapRound);
    CGContextSetLineWidth(UIGraphicsGetCurrentContext(),lineWidth);
    CGContextSetBlendMode(UIGraphicsGetCurrentContext(), kCGBlendModeClear);
    
    CGContextSetRGBStrokeColor(UIGraphicsGetCurrentContext(), red, green, blue, 1.0);
    CGContextBeginPath(UIGraphicsGetCurrentContext());  
    CGContextSetShouldAntialias(UIGraphicsGetCurrentContext(), YES);
    
    CGContextMoveToPoint(UIGraphicsGetCurrentContext(), lastPoint1.x, lastPoint1.y);
    CGContextAddLineToPoint(UIGraphicsGetCurrentContext(), currentPoint.x, currentPoint.y);
    CGContextStrokePath(UIGraphicsGetCurrentContext());
    imgBlankView.image = UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    
    0 讨论(0)
  • 2020-12-08 18:41

    If you know what area you want to erase, you can create a new image of the same size, set the mask to the full image minus the area you want to erase, draw the full image into the new image, and use that as the new image. To undo, simply use the previous image.

    Edit

    Sample code. Say the area you want to erase from image view imgView is specified with by erasePath:

    - (void) clipImage 
    {
        UIImage *img = imgView.image;
        CGSize s = img.size;
        UIGraphicsBeginImageContext(s);
        CGContextRef g = UIGraphicsGetCurrentContext();
        CGContextAddPath(g,erasePath);
        CGContextAddRect(g,CGRectMake(0,0,s.width,s.height));
        CGContextEOClip(g);
        [img drawAtPoint:CGPointZero];
        imageView.image = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
    }
    
    0 讨论(0)
提交回复
热议问题