方法一(原生支持,简单明了,最大的问题是在tableview里面会拖慢速度,感觉会卡):
self.imageView.layer.cornerRadius = 4;
self.imageView.layer.masksToBounds = YES;
方法二:
@implementation ImageUtils
//把图片切成圆角代码
static void addRoundedRectToPath(CGContextRef context,CGRect rect, float ovalWidth,
float ovalHeight,float radius)
{
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, radius); // Top right corner
CGContextAddArcToPoint(context, 0, fh, 0, fh/2, radius); // Top left corner
CGContextAddArcToPoint(context, 0, 0, fw/2, 0, radius); // Lower left corner
CGContextAddArcToPoint(context, fw, 0, fw, fh/2, radius); // Back to lower right
CGContextClosePath(context);
CGContextRestoreGState(context);
}
+ (id) createRoundedRectImage:(UIImage*)image size:(CGSize)size radius:(float) radius
{
// the size of CGContextRef
int w = size.width*2; //解决图像模糊问题
int h = size.height*2; //解决图像模糊问题
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, 10, 10 ,radius);
CGContextClosePath(context);
CGContextClip(context);
CGContextDrawImage(context, CGRectMake(0, 0, w, h), image.CGImage);
CGImageRef imageMasked = CGBitmapContextCreateImage(context);
CGContextRelease(context);
CGColorSpaceRelease(colorSpace);
return [UIImageimageWithCGImage:imageMasked];
}
@end
参考文章:
http://www.cocoachina.com/bbs/read.php?tid=1757&page=1
http://www.cocoachina.com/bbs/read.php?tid=73051&page=2