图片的圆角化

一、将矩形图片处理成圆角图片,放到UIImageView里面显示:

 1 /*create round rect UIImage with the specific size*/  
 2 + (UIImage *) createRoundedRectImage:(UIImage*)image size:(CGSize)size  
 3 {  
 4     // the size of CGContextRef  
 5     int w = size.width;  
 6     int h = size.height;  
 7       
 8     UIImage *img = image;  
 9     CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();  
10     CGContextRef context = CGBitmapContextCreate(NULL, w, h, 8, 4 * w, colorSpace, kCGImageAlphaPremultipliedFirst);  
11     CGRect rect = CGRectMake(0, 0, w, h);  
12       
13     CGContextBeginPath(context);  
14     AddRoundedRectToPath(context, rect, 24, 24);  
15     CGContextClosePath(context);  
16     CGContextClip(context);  
17     CGContextDrawImage(context, CGRectMake(0, 0, w, h), img.CGImage);  
18     CGImageRef imageMasked = CGBitmapContextCreateImage(context);  
19     CGContextRelease(context);  
20     CGColorSpaceRelease(colorSpace);  
21     return [UIImage imageWithCGImage:imageMasked];  
22       
23 }  
24 
25 static void AddRoundedRectToPath(CGContextRef context, CGRect rect, float ovalWidth, float ovalHeight)  
26 {  
27     float fw, fh;  
28     if (ovalWidth == 0 || ovalHeight == 0) {  
29         CGContextAddRect(context, rect);  
30         return;  
31     }  
32       
33     CGContextSaveGState(context);  
34     CGContextTranslateCTM(context, CGRectGetMinX(rect), CGRectGetMinY(rect));  
35     CGContextScaleCTM(context, ovalWidth, ovalHeight);  
36     fw = CGRectGetWidth(rect) / ovalWidth;  
37     fh = CGRectGetHeight(rect) / ovalHeight;  
38       
39     CGContextMoveToPoint(context, fw, fh/2);  // Start at lower right corner  
40     CGContextAddArcToPoint(context, fw, fh, fw/2, fh, 1);  // Top right corner  
41     CGContextAddArcToPoint(context, 0, fh, 0, fh/2, 1); // Top left corner  
42     CGContextAddArcToPoint(context, 0, 0, fw/2, 0, 1); // Lower left corner  
43     CGContextAddArcToPoint(context, fw, 0, fw, fh/2, 1); // Back to lower right  
44       
45     CGContextClosePath(context);  
46     CGContextRestoreGState(context);  
47 }  

实际使用中遇到的注意事项:
        用的比较多的情况就是显示第三方程序图标,也要显示57*57的圆角图标,由于服务器抓取到的第三方程序图标尺寸各异,客户端按照服务器给的地址去取图标之后,不能直接应用这个创建圆角图标的方法,而是应该先将原图尺寸处理成114*114(为了保证Retina屏幕下图标效果不失真,因此没有转为57*57),然后再进行圆角处理,才能保证显示的圆角图标效果类似于苹果手机上的效果。若抓取到的原图非常大,直接使用上述方法,圆角角度非常小,基本没效果,如果都是非常大的图片,那就应该自己调整ovalWidth、ovalHeight这两个参数的值了。
二、直接对UIImageView的layer层进行操作,设置边角的弧度,然后将该view的clipsToBounds属性设为YES

1 UIImageView *roundRectView = [[UIImageView alloc] init];  
2 [roundRectView.layer setCornerRadius:7.5];  
3 roundRectView.clipsToBounds = YES;  
4 [self.view addSubview:roundRectView];  

然后将图片set给这个view,就会使矩形图片的边角被切掉,形成圆角图标显示效果。

posted @ 2013-12-16 20:30  激情为梦想而生  阅读(262)  评论(0编辑  收藏  举报