只需用矩形屏蔽UIView即可 [英] Simply mask a UIView with a rectangle
问题描述
我想知道如何简单地掩盖任何类型的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屋!