Works for any UIView, not just images.
QuartzCore.framework to the list of frameworks.#import <QuartzCore/QuartzCore.h> in the header file.// Rounded corners CALayer *layer = [myView layer]; [layer setMasksToBounds:YES]; [layer setCornerRadius:3.0];
Please note that this method is relatively slow so using it for UITableView icons might feel a little sluggish.
CoreGraphics.framework to the list of frameworks.UIImage class:
UIImageHelloAdditions.h:
@interface UIImage (Hello) // Rounded corners - (UIImage *)roundCornerImageWithWidth:(NSUInteger)ovalWidth height:(NSUInteger)ovalHeight; @end
UIImageHelloAdditions.m:
#import "UIImageHelloAdditions.h" @implementation UIImage (Hello) - (UIImage *)roundCornerImageWithWidth:(NSUInteger)ovalWidth height:(NSUInteger)ovalHeight { UIImage *newImage = nil; // Initialize NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; int w = self.size.width; int h = self.size.height; CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); CGContextRef context = CGBitmapContextCreate(NULL, w, h, 8, 4 * w, colorSpace, kCGImageAlphaPremultipliedFirst); CGContextBeginPath(context); CGRect rect = CGRectMake(0, 0, self.size.width, self.size.height); // Add rounded rect float fw, fh; if (ovalWidth == 0 || ovalHeight == 0) { CGContextAddRect(context, rect); return nil; } 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); CGContextAddArcToPoint(context, fw, fh, fw/2, fh, 1); CGContextAddArcToPoint(context, 0, fh, 0, fh/2, 1); CGContextAddArcToPoint(context, 0, 0, fw/2, 0, 1); CGContextAddArcToPoint(context, fw, 0, fw, fh/2, 1); CGContextClosePath(context); CGContextRestoreGState(context); // Clean up CGContextClosePath(context); CGContextClip(context); CGContextDrawImage(context, CGRectMake(0, 0, w, h), self.CGImage); CGImageRef imageMasked = CGBitmapContextCreateImage(context); CGContextRelease(context); CGColorSpaceRelease(colorSpace); newImage = [[UIImage imageWithCGImage:imageMasked] retain]; CGImageRelease(imageMasked); [pool release]; return newImage; } @end
Now, #import "UIImageHelloAdditions.h" wherever you want to get rounded corners and use the
- (UIImage *)roundCornerImageWithWidth:(NSUInteger)ovalWidth height:(NSUInteger)ovalHeight
method to get those.