How to preload images in iOS

- by

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!



If you enjoy my content, please consider supporting me on Ko-fi. In return you can browse this whole site without any pesky ads! More details here.

Leave a Comment!

This site uses Akismet to reduce spam. Learn how your comment data is processed.