我有一个问题。我在网上寻找答案,我不明白为什么不工作。我必须做一些我无法弄明白的愚蠢错误。
如果我做:
- (void)viewDidLoad
{
[super viewDidLoad];
UIView * view = [[UIView alloc]initWithFrame:CGRectMake(10, 10, 300, 400)];
view.backgroundColor = [UIColor blueColor];
[self.view addSubview:view];
}
它会在屏幕上创建蓝色视图,但如果我创建
- (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)?
答案 0 :(得分:4)
您需要在CAShapeLayer上设置路径:
- (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;
}
答案 1 :(得分:1)
谢谢你的回答,cncool。
如果有人在几个小时内无法在SO上找到合适的答案,就像我刚才那样,我已经在Swift 2.2中为masking
/ clipping
{{1 } UIView
/ CGRect
:
https://gist.github.com/Flar49/7e977e81f1d2827f5fcd5c6c6a3c3d94
UIBezierPath
用法:
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
}
}
希望将来能节省一些时间:)