a) 通常设置图片圆角有两种方式
- 1.代码设置
// 设置头像圆角
self.headIcon.layer.cornerRadius = 24; // 圆角设置为图片宽度一半
self.headIcon.layer.masksToBounds = YES; // 图片超出部分裁剪
- 2.xib/storyboard设置

然而: 这种通过操作
layer
图层的方式去渲染视图(圆角/阴影), 如果过量就会造成页面卡顿, 所以不是很好的方式.
b) 优化方式
-
- (采用绘图), 为
UIImageView
创建一个分类, 实现分类方法circleImage
- (采用绘图), 为
// 设置圆形图片(放到分类中使用)
- (UIImage *)circleImage {
UIGraphicsBeginImageContextWithOptions(self.size, NO, 0.0);
// 获取上下文
CGContextRef ctr = UIGraphicsGetCurrentContext();
// 设置圆形
CGRect rect = CGRectMake(0, 0, self.size.width, self.size.height);
CGContextAddEllipseInRect(ctr, rect);
// 裁剪
CGContextClip(ctr);
// 将图片描绘到圆形画板
[self drawInRect:rect];
// 获取圆形图片
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
// 关闭上下文
UIGraphicsEndImageContext();
// 返回圆形图片
return image;
}
```
- 2.UIView的圆角设置
- 创建UIView的
Category
添加方法
- 创建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;
});
}
```
网友评论