我想知道如何简单地掩盖任何类型的UIView的可见区域.到目前为止,我所阅读的所有答案/教程都描述了用图像,渐变或创建圆角来掩盖,这比我以前的方式更先进.
示例:我有一个带有边界(0,0,100,100)的UIView,我想用掩码切掉视图的右半部分.因此我的面具框架将是(0,0,50,100).
知道怎么做这个简单吗?我不想覆盖drawrect方法,因为这应该适用于任何UIView.
我试过这个,但它只是让整个视图看不见.
CGRect mask = CGRectMake(0, 0, 50, 100);
UIView *maskView = [[UIView alloc] initWithFrame:mask];
viewToMask.layer.mask = maskView.layer;
Run Code Online (Sandbox Code Playgroud)
Acc*_*yyc 125
感谢MSK的链接,这是我使用的方式,效果很好:
// 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;
Run Code Online (Sandbox Code Playgroud)
Fla*_*lar 22
谢谢你的回答.
如果有人几个小时都找不到适合这个问题的答案,就像我刚刚做的那样,我已经在Swift 2.2中组装了一个工作要点for masking/ clipping UIViewwith CGRect/ UIBezierPath:
https://gist.github.com/Flar49/7e977e81f1d2827f5fcd5c6c6a3c3d94
extension UIView {
func mask(withRect rect: CGRect, inverse: Bool = false) {
let path = UIBezierPath(rect: rect)
let maskLayer = CAShapeLayer()
if inverse {
path.append(UIBezierPath(rect: self.bounds))
maskLayer.fillRule = kCAFillRuleEvenOdd
}
maskLayer.path = path.cgPath
self.layer.mask = maskLayer
}
func mask(withPath path: UIBezierPath, inverse: Bool = false) {
let path = path
let maskLayer = CAShapeLayer()
if inverse {
path.append(UIBezierPath(rect: self.bounds))
maskLayer.fillRule = kCAFillRuleEvenOdd
}
maskLayer.path = path.cgPath
self.layer.mask = maskLayer
}
}
Run Code Online (Sandbox Code Playgroud)
用法:
let viewSize = targetView.bounds.size
let rect = CGRect(x: 20, y: 20, width: viewSize.width - 20*2, height: viewSize.height - 20*2)
// Cuts rectangle inside view, leaving 20pt borders around
targetView.mask(withRect: rect, inverse: true)
// Cuts 20pt borders around the view, keeping part inside rect intact
targetView.mask(withRect: rect)
Run Code Online (Sandbox Code Playgroud)
希望将来能节省一些时间:)
Ger*_*eri 20
根本不需要任何面具.只需将其放入包含较小框架的包装视图中,然后设置clipsToBounds即可.
wrapper.clipsToBounds = YES;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
60720 次 |
| 最近记录: |