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了 。。。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM