CAShapeLayer遮罩视图

我有一个问题。 我在网上寻找答案,我不明白为什么不工作。 我必须做一些愚蠢的错误,我无法弄清楚。

如果我做:

- (void)viewDidLoad { [super viewDidLoad]; UIView * view = [[UIView alloc]initWithFrame:CGRectMake(10, 10, 300, 400)]; view.backgroundColor = [UIColor blueColor]; [self.view addSubview:view]; } 

它在屏幕上创build蓝色的视图,但如果我做

 - (void)viewDidLoad { [super viewDidLoad]; UIView * view = [[UIView alloc]initWithFrame:CGRectMake(10, 10, 300, 400)]; view.backgroundColor = [UIColor blueColor]; [self.view addSubview:view]; CAShapeLayer * layer = [[CAShapeLayer alloc]init]; layer.frame = CGRectMake(10, 10, 30, 30); layer.fillColor = [[UIColor blackColor] CGColor]; view.layer.mask = layer; } 

它不显示任何东西。

如果我理解正确,应该在(10,10,30,30)处掩?

您需要在CAShapeLayer上设置path:

 - (void)viewDidLoad { [super viewDidLoad]; UIView * view = [[UIView alloc]initWithFrame:CGRectMake(10, 10, 300, 400)]; view.backgroundColor = [UIColor blueColor]; [self.view addSubview:view]; CAShapeLayer * layer = [[CAShapeLayer alloc]init]; layer.frame = view.bounds; layer.fillColor = [[UIColor blackColor] CGColor]; layer.path = CGPathCreateWithRect(CGRectMake(10, 10, 30, 30), NULL); view.layer.mask = layer; } 

感谢您的回答,cncool。

如果有人在这个问题上几个小时没有find合适的答案,就像我刚才那样,我已经在Swift 2.2中组装了一个工作要点来masking / clipping UIViewCGRect / 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.appendPath(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.appendPath(UIBezierPath(rect: self.bounds)) maskLayer.fillRule = kCAFillRuleEvenOdd } maskLayer.path = path.CGPath self.layer.mask = maskLayer } } 

用法:

 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) 

希望将来可以节省一些时间:)