2011-01-16

UIGraphicsBeginImageContext on iPhone 4

I generate UIImages in some of my iOS applications, and prior to the iPhone 4 they all worked fine. With the introduction of the iPhone 4 and Retina Display, I realised my generated images were blurry even though I am rendering them at twice the resolution.

It turns out this is due to the scale property of my generated UIImages being set to 1. This is mainly due to my use of UIGraphicsBeginImageContext(), which creates a bitmap context that is a) non-opaque and b) scale=1. The fix is quite simple - use UIGraphicsBeginImageContextWithOptions() and specify the scale appropriately.

For images derived from an existing image, e.g. rotating an existing image, it is sufficient to use the scale property of UIImage. For images created "from scratch", I use the following bit of code:
if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)])
{
  UIGraphicsBeginImageContextWithOptions(size, NO, [UIScreen mainScreen].scale);
}
else UIGraphicsBeginImageContext(size);

Cheers,
Steve