美文网首页
如何使用UIBezierPath、CAShapeLayer设置带

如何使用UIBezierPath、CAShapeLayer设置带

作者: 大宝来巡山 | 来源:发表于2021-06-07 18:26 被阅读0次

使用UIBezierPath、CAShapeLayer设置带边框圆角,内存占用最小且渲染快速,避免了离屏渲染带来的性能损耗,不多说,看代码

//任意圆角 带边框大小颜色 ; 当设置borderWidth为0 或者borderColor为透明色 移除layer
- (void)shapeLayerCornerRadiusWithRectCorner:(UIRectCorner)rectCorner cornerRadius:(CGFloat)cornerRadius borderColor:(UIColor*)borderColor borderWidth:(CGFloat)borderWidth {
    //使用UIBezierPath 和 CAShapeLayer 设置圆角 内存占用最小且渲染快速
    if (cornerRadius==0) {
        [self shapeLayerCornerRadiusWithRectCorner:rectCorner];
        return;
    }
    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:self.bounds cornerRadius:cornerRadius];
    
    CAShapeLayer *maskLayer = [[CAShapeLayer alloc]init];
    //设置大小
    maskLayer.frame = self.bounds;
    //设置图形样子
    maskLayer.path = maskPath.CGPath;
    //设置边框大小颜色 中间透明
    maskLayer.strokeColor = borderColor.CGColor;
    maskLayer.lineWidth = borderWidth;
    maskLayer.fillColor  = [UIColor clearColor].CGColor;
    
    //当设置borderWidth为0 或者borderColor为透明色 移除
    if (borderWidth == 0 || borderColor == UIColor.clearColor) {
        
       NSArray<CALayer *> *subLayers = self.layer.sublayers;
       NSArray<CALayer *> *removedLayers = [subLayers filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(id  _Nullable evaluatedObject, NSDictionary<NSString *,id> * _Nullable bindings) {
           return [evaluatedObject isKindOfClass:[CAShapeLayer class]];
       }]];
       [removedLayers enumerateObjectsUsingBlock:^(CALayer * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
           [obj removeFromSuperlayer];
       }];
        
    }else{
        [self.layer insertSublayer:maskLayer atIndex:0];
    } 
}

相关文章

网友评论

      本文标题:如何使用UIBezierPath、CAShapeLayer设置带

      本文链接:https://www.haomeiwen.com/subject/qpxreltx.html