Drawing on top of UIImageView to make the image transparent

天涯浪子 提交于 2019-12-04 10:15:36

The UIImageView has a layer which you can refer to as its layer and talk to when you've linked your project to QuartzCore. As the user moves a finger, clip a clear shape in an opaque-color-filled graphics context the same size as the UIImageView, turn that into a CGImageRef, set that as a CALayer's contents (again this CALayer needs to be the same size as the UIImageView), and set that layer as the UIImageView's layer.mask. Wherever the mask is clear, that punches a transparent hole in the layer, which means the view, which means the image the UIImageView is showing. (If that doesn't work, because the UIImageView doesn't like your interfering with its layer, you can use a superview of the UIImageView instead.)

EDIT (next day) - Here's sample code for a layer's delegate that punches a circular hole in the center:

-(void)drawLayer:(CALayer *)layer inContext:(CGContextRef)c {
    CGRect r = CGContextGetClipBoundingBox(c);
    CGRect r2 = CGRectInset(r, r.size.width/2.0 - 10, r.size.height/2.0 - 10);

    UIImage* maskim;
    {
        UIGraphicsBeginImageContextWithOptions(r.size, NO, 0);
        CGContextRef c = UIGraphicsGetCurrentContext();
        CGContextAddEllipseInRect(c, r2);
        CGContextAddRect(c, r);
        CGContextEOClip(c);
        CGContextSetFillColorWithColor(c, [UIColor blackColor].CGColor);
        CGContextFillRect(c, r);
        maskim = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
    }

    CALayer* mask = [CALayer layer];
    mask.frame = r;
    mask.contents = (id)maskim.CGImage;
    layer.mask = mask;
}

So, if that layer is a view's layer, and if the UIImageView is that view's subview, a hole is punched in the UIImageView.

Here's a screen shot of the result:

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!