iPhone – Round Image Corner

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);
	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);

- (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);

	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);

	CGContextDrawImage(context, CGRectMake(0, 0, w, h), source.CGImage);

	CGImageRef imageMasked = CGBitmapContextCreateImage(context);
	UIImage *newImage = [[UIImage imageWithCGImage:imageMasked] retain];


	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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.