UIImage with rounded corners

iWheelBuy picture iWheelBuy · May 12, 2012 · Viewed 32.5k times · Source

I have read several posts already. And almost everyone suggest using QuartzCore/QuartzCore.h with layer.cornerRadius

I have tried this method and some more methods.

Well, everything works fine when an image doesn't move.

But in my project I always move my images. If I add corner radius or a shadow the image movement is no longer smooth. And it looks aweful!

That is the way I resize my image:

CGSize newSize = CGSizeMake(200*height/image.size.height, 280);
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGContextRef context = CGBitmapContextCreate(nil, newSize.width, newSize.height, 8, 0, colorSpace, kCGImageAlphaPremultipliedLast);
CGContextClearRect(context, CGRectMake(0, 0, newSize.width, newSize.height));
CGContextDrawImage(context, CGRectMake(0, 0, newSize.width, newSize.height), image.CGImage);
CGImageRef scaledImage = CGBitmapContextCreateImage(context);
CGColorSpaceRelease(colorSpace);
CGContextRelease(context);
UIImage *newImage = [UIImage imageWithCGImage: scaledImage];
CGImageRelease(scaledImage);

I would like to know a good way to resize my image, add shadow, corner radius and still have smooth movement of my image.

Answer

MCKapur picture MCKapur · May 12, 2012
// Get your image somehow
UIImage *image = [UIImage imageNamed:@"image.jpg"];

// Begin a new image that will be the new image with the rounded corners 
// (here with the size of an UIImageView)
 UIGraphicsBeginImageContextWithOptions(imageView.bounds.size, NO, [UIScreen mainScreen].scale);

 // Add a clip before drawing anything, in the shape of an rounded rect
  [[UIBezierPath bezierPathWithRoundedRect:imageView.bounds 
                        cornerRadius:10.0] addClip];
 // Draw your image
[image drawInRect:imageView.bounds];

 // Get the image, here setting the UIImageView image
  imageView.image = UIGraphicsGetImageFromCurrentImageContext();

 // Lets forget about that we were drawing
  UIGraphicsEndImageContext();

Try moving with this code, as far as I can remember I used this a while back that makes an image with rounded corners that you can move around into the targets. But it seemed to scale fine...