iOS實(shí)現(xiàn)遮罩鏤空效果2種方式

【1】
- (void)addMask{
    /*
   mask不是遮罩,不是add到layer上的另一個(gè)layer,而是控制layer本身渲染的一個(gè)layer。
    效果是:比如imageLayer有一個(gè)maskLayer作為mask(注意maskLayer可以不跟imageLayer大小一樣),
    那maskLayer透明的地方,imageLayer就不會(huì)渲染,而是變透明,顯示出imageLayer之后的內(nèi)容,
    maskLayer不透明的地方,imageLayer就會(huì)正常渲染,顯示出imageLayer本來(lái)的內(nèi)容
    如果maskLayer比imageLayer要小,那默認(rèn)的maskLayer之外的地方都是透明的,都不會(huì)渲染。
    
    注意:作為mask的layer不能有superLayer或者subLayer!
    
    */
    
        UIView *backgroundView = [[UIView alloc] init];
        backgroundView.frame = self.bounds;
        
        //背景色不能為透明
        backgroundView.backgroundColor = [UIColor colorWithWhite:0 alpha:0.7];
        [self addSubview:backgroundView];
    
        // 創(chuàng)建一個(gè)全屏大的path
         UIBezierPath *path = [UIBezierPath bezierPathWithRect:self.bounds];
         // 創(chuàng)建一個(gè)圓形path
    UIBezierPath *circlePath = [UIBezierPath bezierPathWithArcCenter:CGPointMake(self.center.x/2, self.center.y *3/2)radius:SCREEN_WIDTH/5 startAngle:0 endAngle:2 * M_PI clockwise:NO];
    
    
    // UIBezierPath 有個(gè)原生的方法- (void)appendPath:(UIBezierPath *)bezierPath, 這個(gè)方法作用是倆個(gè)路徑有疊加的部分則會(huì)鏤空.
    //  這個(gè)方法實(shí)現(xiàn)原理應(yīng)該是path的FillRule 默認(rèn)是FillRuleEvenOdd(CALayer 有一個(gè)fillRule屬性的規(guī)則就有kCAFillRuleEvenOdd), 而EvenOdd 是一個(gè)奇偶規(guī)則,奇數(shù)則顯示,偶數(shù)則不顯示.疊加則是偶數(shù)故不顯示
    
         [path appendPath:circlePath];
    
         CAShapeLayer *shapeLayer = [CAShapeLayer layer];
         shapeLayer.path = path.CGPath;
    
         backgroundView.layer.mask = shapeLayer;
}
【2】
- (void)addView{

    UIView *backgroundView = [[UIView alloc] init];
    backgroundView.frame = self.bounds;
  
    //必須透明
    backgroundView.backgroundColor = [UIColor clearColor];
    [self addSubview:backgroundView];
    
    // 創(chuàng)建一個(gè)全屏大的path
    UIBezierPath *path = [UIBezierPath bezierPathWithRect:self.bounds];
    // 創(chuàng)建一個(gè)圓形path
    UIBezierPath *circlePath = [UIBezierPath bezierPathWithArcCenter:CGPointMake(self.center.x/2, self.center.y *3/2)radius:W/5 startAngle:0 endAngle:2 * M_PI clockwise:NO];
    
    CAShapeLayer *shapeLayer = [CAShapeLayer layer];

    [path appendPath:circlePath];
    [path setUsesEvenOddFillRule:YES];
    shapeLayer.path = path.CGPath;
    shapeLayer.fillRule = kCAFillRuleEvenOdd;
    shapeLayer.fillColor = [UIColor blackColor].CGColor;
    shapeLayer.opacity = 0.5;

    [backgroundView.layer addSublayer:shapeLayer];
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容