iOS 圆角优化

在开发过程常遇到控件圆角的设计;我们常用的方式是设置layer属性如下:

self.imageView.layer.cornerRadius = 5;
self.imageView.layer.masksToBounds = YES;

这种处理的渲染机制是GPU在当前屏幕缓冲区外新开辟一个渲染缓冲区进行工作,也就是离屏渲染。如果圆角操作达到一定数量,会触发缓冲区的频繁合并和上下文频繁切换,性能的代价会宏观地表现在用户体验上——掉帧。

方案1:使用贝塞尔曲线UIBezierPath和Core Graphics框架画出一个圆角

 UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(100, 100, 100, 100)];
   imageView.image = [UIImage imageNamed:@"imagename"];
   //开始对imageView进行画图
   UIGraphicsBeginImageContextWithOptions(imageView.bounds.size, NO, 1.0);
   //使用贝塞尔曲线画出一个圆形图
   [[UIBezierPath bezierPathWithRoundedRect:imageView.bounds cornerRadius:imageView.frame.size.width] addClip];
   [imageView drawRect:imageView.bounds];
   imageView.image = UIGraphicsGetImageFromCurrentImageContext();
   UIGraphicsEndImageContext();
   [self.view addSubview:imageView];

方案2:使用CAShapeLayer和UIBezierPath设置圆角

UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(100,100,100,100)];
 imageView.image = [UIImage imageNamed:@"imagename"];
 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];

你可能感兴趣的:(iOS 圆角优化)