在项目中,经常会遇到遮罩效果处理。
其中使用CAShapeLayer
实现遮罩效果最佳。
下面先介绍两种遮罩场景:
正常显示的一个View
遮罩方式一:
遮罩方式二:
遮罩方式一 实现代码:
- (void)viewDidLoad {
[super viewDidLoad];
UIView *view = [[UIView alloc] init];
view.frame = CGRectMake(110.0, 100.0, 100.0, 100.0);
view.backgroundColor = [UIColor purpleColor];
[self.view addSubview:view];
view.layer.mask = [self maskStyle1:view.bounds];
}
- (CAShapeLayer *)maskStyle1:(CGRect)rect {
CGFloat x = rect.size.width/2.0;
CGFloat y = rect.size.height/2.0;
CGFloat radius = MIN(x, y)*0.8;
//
UIBezierPath *cycle = [UIBezierPath bezierPathWithArcCenter:CGPointMake(x, y)
radius:radius
startAngle:0.0
endAngle:2*M_PI
clockwise:YES];
//
CAShapeLayer *maskLayer = [CAShapeLayer layer];
maskLayer.path = [cycle CGPath];
maskLayer.fillRule = kCAFillRuleNonZero;
return maskLayer;
}
遮罩方式二 实现代码:
- (void)viewDidLoad {
[super viewDidLoad];
UIView *view = [[UIView alloc] init];
view.frame = CGRectMake(110.0, 100.0, 100.0, 100.0);
view.backgroundColor = [UIColor purpleColor];
[self.view addSubview:view];
view.layer.mask = [self maskStyle2:view.bounds];
}
- (CAShapeLayer *)maskStyle2:(CGRect)rect {
//
UIBezierPath *path = [UIBezierPath bezierPathWithRect:rect];
CGFloat x = rect.size.width/2.0;
CGFloat y = rect.size.height/2.0;
CGFloat radius = MIN(x, y)*0.8;
//
UIBezierPath *cycle = [UIBezierPath bezierPathWithArcCenter:CGPointMake(x, y)
radius:radius
startAngle:0.0
endAngle:2*M_PI
clockwise:YES];
[path appendPath:cycle];
//
CAShapeLayer *maskLayer = [CAShapeLayer layer];
maskLayer.path = [path CGPath];
maskLayer.fillRule = kCAFillRuleEvenOdd;
return maskLayer;
}
其中关键点是 CAShapeLayer
的fillRule
属性,该属性有两个值,分别为kCAFillRuleNonZero
和kCAFillRuleEvenOdd
。
non-zero
解释为非零;even-odd
解释为奇偶。