您的位置:首页 > 移动开发 > IOS开发

iOS设置圆角图片的方法及对比

2016-03-31 23:59 393 查看
一、我们最常用的方法是:

[view.layer setCornerRadius:10];

这样设置会出发离屏渲染,比较消耗性能,如果一个界面上有多个view这样设置圆角,就会出现明显卡顿(png的图片在iOS9.0之后不会离屏渲染)。

设置圆角后,shouldRasterize=YES光栅化,例如:

imageView.clipsToBounds = YES;
[imageView.layer setCornerRadius:50];
imageView.layer.shouldRasterize = YES;
imageViewUrl.layer.rasterizationScale=[UIScreen mainScreen].scale;  //UIImageView不加这句会产生一点模糊

shouldRasterize=YES设置光栅化,可以使离屏渲染的结果缓存到内存中存为位图,
使用的时候直接使用缓存,节省了一直离屏渲染损耗的性能。
但是如果layer及sublayers常常改变的话,它就会一直不停的渲染及删除缓存重新
创建缓存,所以这种情况下建议不要使用光栅化,这样也是比较损耗性能的。

二、直接覆盖一张中间为圆形透明的图片

这种方法GPU计算多层的混合渲染blending也是会消耗一点性能的,但比第一种方法还是好上很多的。

三、UIImage
drawInRect绘制圆角


这种方式GPU损耗低内存占用大,而且UIButton上不知道怎么绘制,可以用
UIimageView添加个点击手势当做UIButton使用。

UIGraphicsBeginImageContextWithOptions(avatarImageView.bounds.size, NO, [UIScreen mainScreen].scale);
[[UIBezierPath bezierPathWithRoundedRect:avatarImageView.bounds
cornerRadius:50] addClip];
[image drawInRect:avatarImageView.bounds];
avatarImageView.image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();


四、SDWebImage处理图片时Core Graphics绘制圆角

//UIImage绘制为圆角
int w = imageSize.width;
int h = imageSize.height;
int radius = imageSize.width/2;

UIImage *img = image;
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGContextRef context = CGBitmapContextCreate(NULL, w, h, 8, 4 * w, colorSpace, kCGImageAlphaPremultipliedFirst);
CGRect rect = CGRectMake(0, 0, w, h);

CGContextBeginPath(context);
addRoundedRectToPath(context, rect, radius, radius);
CGContextClosePath(context);
CGContextClip(context);
CGContextDrawImage(context, CGRectMake(0, 0, w, h), img.CGImage);
CGImageRef imageMasked = CGBitmapContextCreateImage(context);
img = [UIImage imageWithCGImage:imageMasked];

CGContextRelease(context);
CGColorSpaceRelease(colorSpace);
CGImageRelease(imageMasked);

总结:建议使用第二种方法,本人水平有限,欢迎纠错指正。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: