只需用矩形遮罩 UIView [英] Simply mask a UIView with a rectangle

查看:16
本文介绍了只需用矩形遮罩 UIView的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何简单地屏蔽任何类型的 UIView 的可见区域.到目前为止,我读过的所有答案/教程都描述了使用图像、渐变或创建圆角进行遮罩,这比我所追求的要先进得多.

I want to know how to simply mask the visible area of a UIView of any kind. All the answers/tutorials I've read so far describe masking with an image, gradient or creating round corners which is way more advanced than what I am after.

示例:我有一个边界为 (0, 0, 100, 100) 的 UIView,我想使用遮罩切掉视图的右半部分.因此,我的蒙版框将是 (0, 0, 50, 100).

Example: I have a UIView with the bounds (0, 0, 100, 100) and I want to cut away the right half of the view using a mask. Therefore my mask frame would be (0, 0, 50, 100).

知道如何简单地做到这一点吗?我不想覆盖 drawrect 方法,因为这应该适用于任何 UIView.

Any idea how to do this simply? I don't want to override the drawrect method since this should be applicable to any UIView.

我试过了,但它只会让整个视图不可见.

I've tried this but it just makes the whole view invisible.

CGRect mask = CGRectMake(0, 0, 50, 100);
UIView *maskView = [[UIView alloc] initWithFrame:mask];
viewToMask.layer.mask = maskView.layer;

推荐答案

感谢 MSK 提供的链接,这是我采用的方法,效果很好:

Thanks to the link from MSK, this is the way I went with which works well:

// Create a mask layer and the frame to determine what will be visible in the view.
CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
CGRect maskRect = CGRectMake(0, 0, 50, 100);

// Create a path with the rectangle in it.
CGPathRef path = CGPathCreateWithRect(maskRect, NULL);

// Set the path to the mask layer.
maskLayer.path = path;

// Release the path since it's not covered by ARC.
CGPathRelease(path);

// Set the mask of the view.
viewToMask.layer.mask = maskLayer;

这篇关于只需用矩形遮罩 UIView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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