a) 通常設(shè)置圖片圓角有兩種方式
- 1.代碼設(shè)置
// 設(shè)置頭像圓角
self.headIcon.layer.cornerRadius = 24; // 圓角設(shè)置為圖片寬度一半
self.headIcon.layer.masksToBounds = YES; // 圖片超出部分裁剪
- 2.xib/storyboard設(shè)置
然而: 這種通過操作
layer
圖層的方式去渲染視圖(圓角/陰影), 如果過量就會(huì)造成頁面卡頓, 所以不是很好的方式.
b) 優(yōu)化方式
-
- (采用繪圖), 為
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
添加方法
- 創(chuàng)建UIView的
-(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;
});
}
```