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

查看:61
本文介绍了如何在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.

任何线索都将受到赞赏。

Any clues will be appreciated.

推荐答案

我一直在研究这个问题几个小时,并且有一个我认为可以做你想做的解决方案。首先,使用您认为合适的任何方式创建掩蔽图像。请注意,我们这里只需要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天全站免登陆