UIGraphicsBeginImageContext and retina display

To support retina display, you need to set the scale of UIImage correctly. If you use UIGraphicsBeginImageContext to create offline image, you should use UIGraphicsBeginImageContextWithOptions instead to set the correct scale of the image. Below is the help function that will call with correct scale according to the scale of current device and will use the old function if the OS version of the device is below 4.0 that UIGraphicsBeginImageContextWithOptions is not available.

To use the code, simply replace all UIGraphicsBeginImageContext with RetinaAwareUIGraphicsBeginImageContext

Updated(2010/09/07): Previous code crash on iPad that have scale method but not UIGraphicsBeginImageContextWithOptions function. And the scale wil return 2.0 with in 2x mode.
http://www.waterworld.com.hk/en/blog/uiscreen-and-scale


void RetinaAwareUIGraphicsBeginImageContext(CGSize size) {
static CGFloat scale = -1.0;
if (scale<0.0) {
UIScreen *screen = [UIScreen mainScreen];
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 4.0) {
scale = [screen scale];
}
else {
scale = 0.0; // mean use old api
}
}
if (scale>0.0) {
UIGraphicsBeginImageContextWithOptions(size, NO, scale);
}
else {
UIGraphicsBeginImageContext(size);
}
}