How to preload images in iOS

When you’re displaying a UIImage in your view controller it’s hardly noticeable how long it actually takes for the engine to “draw” the picture. Lenoard van Driel has tested this and confirms it takes 80ms – or in television terms, 2 frames. That’s something worth putting an audio delay in for.

Drawing several images in the same place takes a long time, and certainly takes the smoothness out of your UI. Once drawn however, iOS can display those images much quicker because they’re magically cached in memory – something we don’t have direct access to before you ask.

The solution is to “pre-draw” or “preload” those images while they’re not in vision. Leonard has written a method which does just that:

- (void)preload:(UIImage *)image
{
    CGImageRef ref = image.CGImage;
    size_t width = CGImageGetWidth(ref);
    size_t height = CGImageGetHeight(ref);
    CGColorSpaceRef space = CGColorSpaceCreateDeviceRGB();
    // CGContextRef context = CGBitmapContextCreate(NULL, width, height, 8, width * 4, space, kCGImageAlphaPremultipliedFirst);
    CGContextRef context = CGBitmapContextCreate(NULL, width, height, 8, width * 4, space, kCGImageAlphaPremultipliedLast);
    
    CGColorSpaceRelease(space);
    CGContextDrawImage(context, CGRectMake(0, 0, width, height), ref);
    CGContextRelease(context);
}

Call this on all your images you’d like to preload, and then access them as normal – resulting in much faster draw times.

Note that kCGImageAlphaPremultipliedLast throws a warning on Xcode 5 (not so in Xcode 4.6.3), but the code compiles and works just fine.

Thanks, Lenoard!





Jay is the CEO and founder of WP Hosting, a boutique style managed WordPress hosting and support service. He has been working with Plesk since version 9 and is a qualified Parallels Automation Professional. In his spare time he likes to develop iOS apps and WordPress plugins, or draw on tablet devices. He blogs about his coding journey at http://wpguru.co.uk and http://pinkstone.co.uk.