如何在 iOS 中屏蔽 UIViews [英] How to mask UIViews in iOS

查看:16
本文介绍了如何在 iOS 中屏蔽 UIViews的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看过类似的问题,但没有找到可行的答案.

I've seen similar questions, but haven't found workable answers.

我想使用灰色图像屏蔽 UIView(需要转换为 alpha 比例进行屏蔽).UIView 有背景.屏蔽图像应该很容易,但我想屏蔽任何 UIView.

I want to mask a UIView using a grey image (need to convert to alpha scale for masking). The UIView has background. It should be easy to mask an image, but I want to mask any UIView.

任何线索将不胜感激.

推荐答案

我已经研究了这个问题几个小时,并且有一个我认为可以满足您的要求的解决方案.首先,使用您认为合适的任何方式创建您的遮罩图像.请注意,这里我们只需要 alpha 值,所有其他颜色都将被忽略,因此请确保您使用的方法支持 alpha 值.在本例中,我从 .png 文件加载,但不要尝试使用 .jpg 文件,因为它们没有 alpha 值.

I've been working on this problem for a couple of hours and have a solution that I think will do what you want. First, create your masking image using whatever means you see fit. Note that we only need the alpha values here, all other colours will be ignored, so make certain that the method you use supports alpha values. In this example I'm loading from a .png file, but don't try it with .jpg files as they don't have alpha values.

接下来,创建一个新层,将您的蒙版分配给它的内容,并将这个新层设置为您的 UIView 自己的层,如下所示:您应该会发现这掩盖了 UIView 及其所有附加的子视图:

Next, create a new layer, assign your mask to its contents and set this new layer to your UIView's own layer, like so: you should find that this masks the UIView and all its attached subviews:

UIImage *_maskingImage = [UIImage imageNamed:@"mask"];
CALayer *_maskingLayer = [CALayer layer];
_maskingLayer.frame = theView.bounds;
[_maskingLayer setContents:(id)[_maskingImage CGImage]];
[theView.layer setMask:_maskingLayer];

完成后,您可以将 UIView 的背景颜色设置为您喜欢的任何颜色,并且遮罩将用于创建彩色过滤器.

With this done, you can set the UIView's background colour to whatever you like and the mask will be used to create a coloured filter.

从 iOS8 开始,您现在可以简单地通过将另一个视图分配给其 maskView 属性来屏蔽视图.一般规则保持不变,因为 maskView 的 alpha 层用于确定它所应用到的视图的不透明度.

As of iOS8 you can now mask a view simply by assigning another view to its maskView property. The general rules stay the same in that the maskView's alpha layer is used to determine the opacity of the view it is applied to.

这篇关于如何在 iOS 中屏蔽 UIViews的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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