If you want to round four corners of an image in your iPhone Application, the following piece of code should help.
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); 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); } - (UIImage *)roundCornersOfImage:(UIImage *)source { int w = source.size.width; int h = source.size.height; CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); CGContextRef context = CGBitmapContextCreate(NULL, w, h, 8, 4 * w, colorSpace, kCGImageAlphaPremultipliedFirst); CGContextBeginPath(context); CGRect rect = CGRectMake(0, 0, w, h); // Set the oval width and height to be quarter of the image width and height addRoundedRectToPath(context, rect, w/4, h/4); CGContextClosePath(context); CGContextClip(context); CGContextDrawImage(context, CGRectMake(0, 0, w, h), source.CGImage); CGImageRef imageMasked = CGBitmapContextCreateImage(context); UIImage *newImage = [[UIImage imageWithCGImage:imageMasked] retain]; CGContextRelease(context); CGColorSpaceRelease(colorSpace); CGImageRelease(imageMasked); return newImage; }
Example: Try to show a rounded image in a UIView
// Create an UIImageView with size 96 x 96 UIImageView *aImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 96, 96)]; // Round the image and set it in the UIImageView aImageView.image [self roundCornersOfImage:<UIImage>];
Done =)
Reference: Rounded corners to images