1. 使用QuartzCore.framework
添加QuartzCore.framework,导入头文件 #import <QuartzCore/QuartzCore.h>
[[imgView layer] setCornerRadius: 10];
[[imgView layer] setMasksToBounds:YES];
static void addRoundedRectToPath(CGContextRef context, CGRect rect, float ovalWidth, float ovalHeight)
{
if (ovalWidth == 0 || ovalHeight == 0 ) {
CGContextAddRect(context, rect);
return;
}
float fw, fh;
CGContextSaveGState(context);
//change the corner size below...
CGContextTranslateCTM(context, CGRectGetMinX(rect), CGRectGetMinY(rect));
CGContextScaleCTM(context, ovalWidth, ovalHeight);
fw = CGRectGetWidth(rect) / ovalWidth;
fh = CGRectGetHeight(rect) / ovalHeight;
CGContextMoveToPoint(context, fw, fh/2);
CGContextAddArcToPoint(context, fw, fh, fw/2, fh, 2.5);
CGContextAddArcToPoint(context, 0, fh, 0, fh/2, 2.5);
CGContextAddArcToPoint(context, 0, 0, fw/2, 0, 2.5);
CGContextAddArcToPoint(context, fw, 0, fw, fh/2, 2.5);
CGContextClosePath(context);
CGContextRestoreGState(context);
}
- (UIImage *)RoundRectImage:(UIImage *)image
{
int width = image.size.width;
int height = image.size.height;
CGColorSpaceRef colorRef = CGColorSpaceCreateDeviceRGB();
CGContextRef context = CGBitmapContextCreate(NULL, width, height, 8, width * 4, colorRef, kCGImageAlphaPremultipliedLast);
CGRect rect = CGRectMake(0, 0, width, height);
CGContextBeginPath(context);
addRoundedRectToPath(context, rect, 10, 10);
CGContextClosePath(context);
CGContextClip(context);
CGContextDrawImage(context, rect, image.CGImage);
CGImageRef imgMask = CGBitmapContextCreateImage(context);
CGColorSpaceRelease(colorRef);
CGContextRelease(context);
return [UIImage imageWithCGImage:imgMask];
}