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

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

问题描述

我正在尝试在 UIImage 中切割一个透明方块,但老实说我不知道​​从哪里/如何开始.

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

任何帮助将不胜感激.

谢谢!

推荐答案

假设您的图像显示在视图中 - 可能是 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天全站免登陆