Tag Archives: UIImage

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:

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

Thanks, Lenoard!

How to convert a UIImage into NSData

You can store a UIImage (or an NSImage on Mac) as raw data. This can be useful if you’d like to save it in Core Data.

Here’s how you convert a UIImage into NSData:

To convert NSData back to a UIImage, you can do this:

The UIImage class is not available on Mac OS X, but its counterpart NSImage is almost identical.



Core Data can convert images to and from data on the fly by using an NSValueTransformer.
Here’s one that works for images:

How to display a UIImage from an NSURL

If you’re displaying images from the main iOS bundle, things are fairly straightforward:

But if you have an NSURL to your image then it’s not as easy. It took me some digging to find out that you have to convert the URL into NSData first, and then display the data:

Convoluted – but currently the only way I know how to do it.

How to load a UIImage that we’ve previously saved

How to save a UIImage

How to select a UIImage from the camera roll (and use it)

The UIImagePickerController can help us do this with ease.

In this example we’ll instantiate an image picker and tell it what kind of image we want returned. We have a choice of using an edited version, use the original, or start using a camera. Next we present the picker from which the user can select the image:


For this to work you need to conform to both the UIImagePickerControllerDelegate protocol, as well as the UINavigationControllerDelegate. The latter does not need to conform to any methods – but without it we’d get a warning.

The two methods we need to conform to the first protocol are dealing with selection and cancellation. In this example I’m displaying the returned image in a UIImageView: