如何在iOS上擦除UIImageView图像的某些部分?

时间:2009-09-28 15:12:09

标签: objective-c iphone core-graphics erase

我有一个UIImageView的视图,并设置了一个图像。我想删除图像就像我们在带有橡皮擦的Photoshop中一样。我该如何实现这一目标?另外,如何撤消擦除?

3 个答案:

答案 0 :(得分:7)

如果您知道要删除的区域,可以创建相同大小的新图像,将蒙版设置为完整图像减去要删除的区域,将完整图像绘制到新图像中,然后使用那是新的形象。要撤消,只需使用上一张图片。

修改

示例代码。假设您要从图片视图imgView中删除要删除的区域由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();
}

答案 1 :(得分:1)

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();

答案 2 :(得分:0)

Swift 5.2 版本

        UIGraphicsBeginImageContextWithOptions(imageView.frame.size, false, 1.0)
        let currentContext = UIGraphicsGetCurrentContext()
        currentContext?.addPath(shapeLayer.path!)
        currentContext?.addRect(CGRect(x: 0, y: 0, width: imageView.frame.size.width, height: imageView.frame.size.height))
        currentContext?.clip(using: .evenOdd)
        
        imageView.image?.draw(at: .zero)
        
        let imageTeemp = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext()