
方法一:通过设置UIView的layer来设置圆角
此方法的有个缺点是:会强制Core Animation提前渲染屏幕的离屏绘制, 而离屏绘制就会给性能带来负面影响,会有卡顿的现象出现
方法二:通过Graphics绘制图片,将图片裁剪成圆角
裁剪后设置图片即可
方法三: 依然是绘制图片,这次是通过贝塞尔曲线绘制图片
绘制后设置UIImageView的图片即可
以上设置图片圆角的三种方法,在使用过程中各有优缺点,需要根据实际情况具体判断使用方法。
另外推荐一下我的导航栏联动库: GKNavigationController
之前面试的时候被问道设置圆角除了layer还有什么方法?因为大家都知道layer会影响app性能,也是大家最常用、最简单的方法。下面就简单介绍这3种方法:
1、通过设置layer的属性
UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(100, 100, 100, 100)]
//只需要设置layer层的两个属性
//设置圆角
imageView.layer.cornerRadius = imageView.frame.size.width / 2
//将多余的部分切掉
imageView.layer.masksToBounds = YES
[self.view addSubview:imageView]
2、第二种方法:使用贝塞尔曲线UIBezierPath和Core Graphics框架画出一个圆角
UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(100, 100, 100, 100)]
imageView.image = [UIImage imageNamed:@"1"]
//开始对imageView进行画图
UIGraphicsBeginImageContextWithOptions(imageView.bounds.size, NO, [UIScreen mainScreen].scale)
//使用贝塞尔曲线画出一个圆形图
[[UIBezierPath bezierPathWithRoundedRect:imageView.bounds cornerRadius:imageView.frame.size.width] addClip]
[imageView drawRect:imageView.bounds]
imageView.image = UIGraphicsGetImageFromCurrentImageContext()
//结束画图
UIGraphicsEndImageContext()
[self.view addSubview:imageView]
3、第三种方法:使用CAShapeLayer和UIBezierPath设置圆角
#warning 首先需要导入
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad]
UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(100, 100, 100, 100)]
imageView.image = [UIImage imageNamed:@"1"]
UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:imageView.bounds byRoundingCorners:UIRectCornerAllCorners cornerRadii:imageView.bounds.size]
CAShapeLayer *maskLayer = [[CAShapeLayer alloc]init]
//设置大小
maskLayer.frame = imageView.bounds
//设置图形样子
maskLayer.path = maskPath.CGPath
imageView.layer.mask = maskLayer
[self.view addSubview:imageView]
}
使用layer
_imageView.clipsToBounds=YES
_imageView.layer.cornerRadius=4.0
评论:在图片较多的TableView里面,卡顿现象较明显,原因是离屏幕渲染消耗性能
实现UIImage的扩展,将原图裁剪成圆角,
评论:在IPhone5s IPhone6上效果好一些,但是在IPhone6s上效果不太明显
子类化UIImageView,给当前image绘制圆角
评论:效果较为明显,卡顿现象基本感觉不到
子类化UIImageView,给UIImageView上面盖一层中间镂空的遮罩
评论:终极解决方案,简单省事效果好
一般项目里面圆角图片类型不会太多,可以根据不用的圆角弧度盖上不同的遮罩,实现不同的需求,我们项目里现在只实现了正圆类型
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)