图片圆角效果显示,目前我用过两种方法。
一、将矩形图片处理成圆角图片,放到UIImageView里面显示。
网上可以查到很多这种方法的代码,算是比较成熟的方法了。
/*create round rect UIImage with the specific size*/
+ (UIImage *) createRoundedRectImage:(UIImage*)image size:(CGSize)size
{
// the size of CGContextRef
int w = size.width;
int h = size.height;
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, 24, 24);
CGContextClosePath(context);
CGContextClip(context);
CGContextDrawImage(context, CGRectMake(0, 0, w, h), img.CGImage);
CGImageRef imageMasked = CGBitmapContextCreateImage(context);
CGContextRelease(context);
CGColorSpaceRelease(colorSpace);
return [UIImage imageWithCGImage:imageMasked];
}
static void AddRoundedRectToPath(CGContextRef context, CGRect rect, float ovalWidth,
float ovalHeight)
{
float fw, fh;
if (ovalWidth == 0 || ovalHeight == 0) {
CGContextAddRect(context, rect);
return;
}
CGContextSaveGState(context);
CGContextTranslateCTM(context, CGRectGetMinX(rect), CGRectGetMinY(rect));
CGContextScaleCTM(context, ovalWidth, ovalHeight);
fw = CGRectGetWidth(rect) / ovalWidth;
fh = CGRectGetHeight(rect) / ovalHeight;
CGContextMoveToPoint(context, fw, fh/2); // Start at lower right corner
CGContextAddArcToPoint(context, fw, fh, fw/2, fh, 1); // Top right corner
CGContextAddArcToPoint(context, 0, fh, 0, fh/2, 1); // Top left corner
CGContextAddArcToPoint(context, 0, 0, fw/2, 0, 1); // Lower left corner
CGContextAddArcToPoint(context, fw, 0, fw, fh/2, 1); // Back to lower right
CGContextClosePath(context);
CGContextRestoreGState(context);
}
注:上述代码非原创。
实际使用中遇到的注意事项:用的比较多的情况就是显示第三方程序图标,也要显示57*57的圆角图标,我曾经遇到过由于服务器抓取到的第三方程序图标尺寸各异,客户端按照服务器给的地址去取图标之后,不能直接应用这个创建圆角图标的方法,而是应该先将原图尺寸处理成114*114(为了保证Retina屏幕下图标效果不失真,因此没有转为57*57),然后再进行圆角处理,才能保证显示的圆角图标效果类似于苹果手机上的效果。曾经遇到抓取到的原图非常大,直接使用上述方法,圆角角度非常小,基本没效果,如果都是非常大的图片,那就应该自己调整ovalWidth、ovalHeight这两个参数的值了。
二、直接对UIImageView的layer层进行操作,设置边角的弧度,然后将该view的clipsToBounds属性设为YES
UIImageView *roundRectView = [[UIImageView alloc] init];
[roundRectView.layer setCornerRadius:7.5];
roundRectView.clipsToBounds = YES;
[self.view addSubview:roundRectView];
然后将图片set给这个view,就会使矩形图片的边角被切掉,形成圆角图标显示效果。
第二种方法比较方便,如果只是将UIImage放在UIImageView里显示,应该没啥问题。
不过到底那种方法好呢??希望有高手能再给说说更深层次有啥区别。layer是个好东西,可惜我不是太会搞,呵呵,不知道对layer操作太对是不是会效率不太高之类的,如果是的话,那第二种方法就不是太可取了。