iOS 兩種遮罩方式

在項目中,經常會遇到遮罩效果處理。
其中使用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;
}

其中關鍵點是 CAShapeLayerfillRule屬性,該屬性有兩個值,分別為kCAFillRuleNonZerokCAFillRuleEvenOdd

non-zero解釋為非零;even-odd解釋為奇偶。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容