How to draw CALayer border around its mask?

后端 未结 6 1450
谎友^
谎友^ 2021-02-07 09:39

So, I have a CALayer, which has a mask & I want to add border around this layer\'s mask. For example, I have set triangle mask to the layer and I want to have b

6条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-02-07 09:46

    Consider this example code:

    - (void)drawRect:(CGRect)rect {
        CAShapeLayer *maskLayer = [CAShapeLayer layer];
    
        //Modify to your needs
        CGFloat maskInsetWidth = 5.0f;
        CGFloat maskInsetHeight = 5.0f;
        CGFloat maskCornerRadius = 5.0f;
        CGFloat borderWidth = 2.0f;
        UIColor *borderColor = [UIColor blackColor];
    
        CGRect insetRect = CGRectInset(self.bounds, maskInsetWidth, maskInsetHeight);
        insetRect.size.width = MAX(insetRect.size.width, 0);
        insetRect.size.height = MAX(insetRect.size.height, 0);
    
        CGPathRef path = [UIBezierPath bezierPathWithRoundedRect:insetRect cornerRadius:maskCornerRadius].CGPath;
    
        if (borderWidth > 0.0f && borderColor != nil) {
            CAShapeLayer *borderLayer = [CAShapeLayer layer];
    
            [borderLayer setPath:path];
            [borderLayer setLineWidth:borderWidth * 2.0f];
            [borderLayer setStrokeColor:borderColor.CGColor];
            [borderLayer setFillColor:[UIColor clearColor].CGColor];
    
            borderLayer.frame = self.bounds;
            [self.layer addSublayer:borderLayer];
        }
        [maskLayer setPath:path];
        [maskLayer setFillRule:kCAFillRuleEvenOdd];
        maskLayer.frame = self.bounds;
        [self.layer setMask:maskLayer];
    }
    

提交回复
热议问题