實現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;
相關文章
相關標籤/搜索