How to scale down an image in iOS, anti-aliased but not soft?

akaru picture akaru · Feb 2, 2012 · Viewed 7.2k times · Source

I have tried the UIImage+Resize category that's popular, and with varying interpolation settings. I have tried scaling via CG methods, and CIFilters. However, I can never get an image downsized that does not either look slightly soft in focus, nor full of jagged artifacts. Is there another solution, or a third party library, which would let me get a very crisp image?

It must be possible on the iPhone, because for instance the Photos app will show a crisp image even when pinching to scale it down.

Answer

justin picture justin · Feb 16, 2012

You said CG, but did not specify your approach.

Using drawing or bitmap context:

CGContextSetInterpolationQuality(gtx, kCGInterpolationHigh);
CGContextSetShouldAntialias(gtx, true); << default varies by context type
CGContextDrawImage(gtx, rect, image);

and make sure your views and their layers are not resizing the image again. I've had good results with this. It's possible other views are affecting your view or the context. If it does not look good, try it in isolation to sanity check whether or not something is distorting your view/image.

If you are drawing to a bitmap, then you create the bitmap with the target dimensions, then draw to that.

Ideally, you will maintain the aspect ratio.

Also note that this can be quite CPU intensive -- repeatedly drawing/scaling in HQ will cost a lot of time, so you may want to create a resized copy instead (using CGBitmapContext).