如何在UIImage中“切割”一个透明的孔? [英] How can I 'cut' a transparent hole in a UIImage?

查看:103
本文介绍了如何在UIImage中“切割”一个透明的孔?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在UIImage中切割一个透明的方块,但是我真的很想知道在哪里/如何开始。

I'm trying to cut an transparent square in a UIImage, however I honestly have to idea where/how to start.

任何帮助将非常感谢。

Any help would be greatly appreciated.

谢谢!

推荐答案

假设您的图片正在显示一个视图 - 可能是一个UIImageView。然后,我们可以通过屏蔽视图的图层在该视图中打出一个矩形孔。每个视图都有一个图层。我们将应用于这个视图的图层一个掩码,它本身是一个包含图像的图层,我们将在代码中生成它。除了在中间某处有一个清晰的矩形,图像将是黑色的。

Presume that your image is being displayed in a view - probably a UIImageView. Then we can punch a rectangular hole in that view by masking the view's layer. Every view has a layer. We will apply to this view's layer a mask which is itself a layer containing an image, which we will generate in code. The image will be black except for a clear rectangle somewhere in the middle. That clear rectangle will cause the hole in the image view.

所以,让 self.iv 是这个UIImageView。尝试运行此代码:

So, let self.iv be this UIImageView. Try running this code:

CGRect r = self.iv.bounds;
CGRect r2 = CGRectMake(20,20,40,40); // adjust this as desired!
UIGraphicsBeginImageContextWithOptions(r.size, NO, 0);
CGContextRef c = UIGraphicsGetCurrentContext();
CGContextAddRect(c, r2);
CGContextAddRect(c, r);
CGContextEOClip(c);
CGContextSetFillColorWithColor(c, [UIColor blackColor].CGColor);
CGContextFillRect(c, r);
UIImage* maskim = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
CALayer* mask = [CALayer layer];
mask.frame = r;
mask.contents = (id)maskim.CGImage;
self.iv.layer.mask = mask;

例如,在此图像中,白色正方形不是重叠的正方形,显示其背后的窗口背景的白色:

For example, in this image, the white square is not a superimposed square, it is a hole, showing the white of the window background behind it:

编辑:我感到有义务,因为我在评论中提到它,以显示如何做同样的事情CAShapeLayer。结果是完全一样的:

EDIT: I feel obligated, since I mentioned it in a comment, to show how to do the same thing with a CAShapeLayer. The result is exactly the same:

CGRect r = self.iv.bounds;
CGRect r2 = CGRectMake(20,20,40,40); // adjust this as desired!
CAShapeLayer* lay = [CAShapeLayer layer];
CGMutablePathRef path = CGPathCreateMutable();
CGPathAddRect(path, nil, r2);
CGPathAddRect(path, nil, r);
lay.path = path;
CGPathRelease(path);
lay.fillRule = kCAFillRuleEvenOdd;
self.iv.layer.mask = lay;

这篇关于如何在UIImage中“切割”一个透明的孔?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆