ios maskView的镂空遮罩实现

1.创建一个镂空的路径:

UIBezierPath 有个原生的方法- (void)appendPath:(UIBezierPath *)bezierPath, 这个方法作用是俩个路径有叠加的部分则会镂空.

这个方法实现原理应该是path的FillRule 默认是FillRuleEvenOdd(CALayer 有一个fillRule属性的规则就有kCAFillRuleEvenOdd), 而EvenOdd 是一个奇偶规则,奇数则显示,偶数则不显示.叠加则是偶数故不显示.

2.创建CAShapeLayer 将镂空path赋值给shapeLayer

3.将shapeLayer 设置为背景视图的Mask

上代码:

- (void)viewDidLoad {
    [super viewDidLoad];

    UIView *backGroundView = [[UIView alloc] initWithFrame:self.view.bounds];

    self.view.backgroundColor = [UIColor grayColor];
    
    backGroundView.backgroundColor = [UIColor whiteColor];
    
    backGroundView.alpha = 0.7;
    
    [self.view addSubview:backGroundView];
    
    UIBezierPath *path = [UIBezierPath bezierPathWithRect:self.view.bounds];
     // 创建一个圆形path
    /*UIBezierPath *circlePath = [UIBezierPath bezierPathWithArcCenter:CGPointMake(self.view.center.x, self.view.center.y - 25)
                                                                                                    radius:50
                                                                                               startAngle:0
                                                                                                  endAngle:2 * M_PI
                                                                                                clockwise:NO];*/
    // 创建矩形
    UIBezierPath *circlePath = [UIBezierPath bezierPathWithRect:CGRectMake(self.view.bounds.size.width / 2 - 100, self.view.bounds.size.height / 2 - 100, 200, 200)];
    
    [path appendPath:circlePath];
    
    CAShapeLayer *shaperLayer = [CAShapeLayer layer];
    shaperLayer.path = circlePath.CGPath;
    backGroundView.layer.mask = shaperLayer;

效果图:

 

当然也可以用无脑的方法解决此类需求 : 直接贴个引导图就OK了 。。。

 

posted @ 2017-03-26 12:22  爱影儿的大花猫  阅读(3948)  评论(0编辑  收藏  举报