切圆角一直是个老生长谈问题,为什么呢?就是因为效率问题选择一个高效的渲染方式是关键。
*注:现在我们不用太担心这个问题了从9.0以后所有的切圆角的方案都不会产生离屏渲染。
下面我们说说切圆角都有哪些方式:
-
设置视图的layer属性:
//设置视图layer层的两个属性
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 30, 100, 100)];
imageView.image = [UIImage imageNamed:@"head.png"];
//设置圆角半径
imageView.layer.cornerRadius = 15.0f;
//将多余的部分切掉
imageView.layer.masksToBounds = YES;
[self.view addSubview:imageView];
效果图:
connerRadius.jpg
优点:方便快捷、代码简单。
缺点:8.0会有离屏渲染效率低下,但是9.0做了优化以后均是主屏渲染。
-
UIImage切圆角
- (void)imageView:(UIImageView *)imageView cornerRadius:(CGFloat)radius
{
//开始对imageView进行画图
UIGraphicsBeginImageContextWithOptions(imageView.bounds.size, NO, [UIScreen mainScreen].scale);
//使用贝塞尔曲线画出一个圆形图
[[UIBezierPath bezierPathWithRoundedRect:imageView.bounds cornerRadius:radius] addClip];
[imageView drawRect: imageView.bounds];
imageView.image = UIGraphicsGetImageFromCurrentImageContext();
//结束画图
UIGraphicsEndImageContext();
}
效果图:
roundedRect.jpg
优点:不会产生离屏渲染
系统:8.0以后均不会产生离屏渲染。
-
通过叠加图层遮挡方式
此方法就是在要添加圆角view上叠加一个中间镂空透明的视图,只对圆角部分进行遮挡,不过同时也需要遮挡颜色和view背景色一致才行。
原图片:
headImage.png masklayer.png
self.view.backgroundColor = [UIColor redColor];
UIImageView *headImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"headImage.png"]];
headImageView.center = CGPointMake(100, 400);
headImageView.size = CGSizeMake(60, 60);
[self.view addSubview:headImageView];
UIImage *image = [UIImage imageNamed:@"masklayer.png"];
UIEdgeInsets insets = UIEdgeInsetsMake(image.size.height/2, image.size.width/2, image.size.height/2, image.size.width/2);
image = [image resizableImageWithCapInsets:insets resizingMode:UIImageResizingModeStretch];
UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
imageView.x = 0;
imageView.y = 0;
imageView.width = headImageView.width;
imageView.height = headImageView.height;
[headImageView addSubview:imageView];
合成后图片:
complex.jpg
优点:此方法也是最优解,没有离屏渲染,没有额外的CPU计算。
缺点:应用范围有限。
-
通过赛贝尔曲线画出镂空layer覆盖到视图上
self.view.backgroundColor = [UIColor greenColor];
UIImageView *headImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"Image_head"]];
headImageView.center = CGPointMake(100, 400);
headImageView.size = CGSizeMake(60, 60);
[self.view addSubview:headImageView];
CAShapeLayer *shapeLayer = [CAShapeLayer layer];
UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(0, 0, headImageView.width, headImageView.height) cornerRadius:0];
[path appendPath:[[UIBezierPath bezierPathWithRoundedRect:CGRectMake(0, 0, headImageView.width, headImageView.height) cornerRadius:20] bezierPathByReversingPath]];
shapeLayer.path = path.CGPath;
shapeLayer.lineWidth = 0;
shapeLayer.strokeColor = [UIColor whiteColor].CGColor;
shapeLayer.fillColor = [UIColor whiteColor].CGColor;
shapeLayer.contentsScale = 20;
shapeLayer.lineCap = kCALineCapRound;
shapeLayer.strokeStart = 0.0f;
shapeLayer.strokeEnd = 0.1f;
[headImageView.layer addSublayer:shapeLayer];
效果图:
UNADJUSTEDNONRAW_thumb_667.jpg
优点:效率最高、内存消耗最少、不会产生离屏渲染、相对图层叠加减少了一张覆盖层图片。
网友评论