实现UIView任意圆角+绘制阴影

给UIView设置圆角时,传统方式都是设置layer的masksToBounds 为 YES时,这种方式会触发离屏渲染(offscreen rendering),导致APP的帧率下降,特别是如果在cell上这么用,tableView滑动时特别耗性能,会有明显卡顿。
 
 CGSize viewSize = self.frame.size;
    CAShapeLayer *maskLayer = [CAShapeLayer layer];
    maskLayer.frame = CGRectMake(0, 0, viewSize.width, viewSize.height);
    
    CAShapeLayer *shapeLayer = [CAShapeLayer layer];
    shapeLayer.frame = CGRectMake(0, 0, viewSize.width, viewSize.height);
    shapeLayer.fillColor = [UIColor clearColor].CGColor;
    shapeLayer.strokeColor = borderColor.CGColor;
    shapeLayer.lineWidth = borderWidth;
    
    UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(0, 0, viewSize.width, viewSize.height) cornerRadius:radius];
    shapeLayer.path = path.CGPath;
    maskLayer.path = path.CGPath;
    
    [self.layer insertSublayer:shapeLayer atIndex:0];
    [self.layer setMask:maskLayer];

 

还有一种更加简单的,还可以解决阴影和图片等冲突问题

self.layer.shadowColor = shadowColor.CGColor;
    self.layer.borderColor = self.layer.shadowColor; // 边框颜色建议和阴影颜色一致
    self.layer.borderWidth = 0.000001; // 只要不为0就行
    self.layer.cornerRadius = radius;
    self.layer.shadowOpacity = shadowOpacity;
    self.layer.shadowRadius = shadowRadius;
    self.layer.shadowOffset = shadowOffset;

 

 

posted @ 2019-04-12 14:23  Nelsen_Chen  阅读(2191)  评论(0编辑  收藏  举报