iOS 两种遮罩方式

在项目中,经常会遇到遮罩效果处理。
其中使用CAShapeLayer实现遮罩效果最佳。
下面先介绍两种遮罩场景:
正常显示的一个View

iOS 两种遮罩方式_第1张图片
需要添加遮罩的视图

遮罩方式一:

iOS 两种遮罩方式_第2张图片
遮罩方式一

遮罩方式二:

iOS 两种遮罩方式_第3张图片
遮罩方式二

遮罩方式一 实现代码:

- (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;
}

其中关键点是 CAShapeLayerfillRule属性,该属性有两个值,分别为kCAFillRuleNonZerokCAFillRuleEvenOdd

non-zero解释为非零;even-odd解释为奇偶。

你可能感兴趣的:(iOS 两种遮罩方式)