優(yōu)化圖片圓角CornerRadius設(shè)置

a) 通常設(shè)置圖片圓角有兩種方式

  • 1.代碼設(shè)置
// 設(shè)置頭像圓角
self.headIcon.layer.cornerRadius = 24;  // 圓角設(shè)置為圖片寬度一半
self.headIcon.layer.masksToBounds = YES;  // 圖片超出部分裁剪
  • 2.xib/storyboard設(shè)置

xib/storyboard設(shè)置

然而: 這種通過操作layer圖層的方式去渲染視圖(圓角/陰影), 如果過量就會(huì)造成頁面卡頓, 所以不是很好的方式.

b) 優(yōu)化方式

    1. (采用繪圖), 為UIImageView創(chuàng)建一個(gè)分類, 實(shí)現(xiàn)分類方法circleImage

// 設(shè)置圓形圖片(放到分類中使用)
- (UIImage *)circleImage {
UIGraphicsBeginImageContextWithOptions(self.size, NO, 0.0);
// 獲取上下文
CGContextRef ctr = UIGraphicsGetCurrentContext();
// 設(shè)置圓形
CGRect rect = CGRectMake(0, 0, self.size.width, self.size.height);
CGContextAddEllipseInRect(ctr, rect);
// 裁剪
CGContextClip(ctr);
// 將圖片描繪到圓形畫板
[self drawInRect:rect];
// 獲取圓形圖片
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
// 關(guān)閉上下文
UIGraphicsEndImageContext();
// 返回圓形圖片
return image;
}
```

  • 2.UIView的圓角設(shè)置
    • 創(chuàng)建UIView的Category添加方法

-(void)setCornerWithRadiu:(CGSize)cornerRadii byRoundCornorners:(UIRectCorner)corner{
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.01 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:self.bounds byRoundingCorners:corner cornerRadii:cornerRadii];
CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
maskLayer.frame = self.bounds;
maskLayer.path = maskPath.CGPath;
self.layer.mask = maskLayer;
});
}
```

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容