在項(xiàng)目中丢氢,經(jīng)常會(huì)遇到遮罩效果處理拇舀。
其中使用CAShapeLayer
實(shí)現(xiàn)遮罩效果最佳孤里。
下面先介紹兩種遮罩場景:
正常顯示的一個(gè)View
需要添加遮罩的視圖
遮罩方式一:
遮罩方式一
遮罩方式二:
遮罩方式二
遮罩方式一 實(shí)現(xiàn)代碼:
- (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;
}
遮罩方式二 實(shí)現(xiàn)代碼:
- (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;
}
其中關(guān)鍵點(diǎn)是 CAShapeLayer
的fillRule
屬性姻政,該屬性有兩個(gè)值傲霸,分別為kCAFillRuleNonZero
和kCAFillRuleEvenOdd
免猾。
non-zero
解釋為非零是辕;even-odd
解釋為奇偶。