Using imageNamed to pick the right image file
When designing an iOS app for different devices in the iOS family, there are a lot of different sizes (and corresponding image files). Rather than having to code all the different cases, UIKit’s UIImage imageNamed can take care of it. This is achieved by using naming conventions, so that UIImage can choose the “right” image file depending on the device the app is running on.
Elements of the “imageNamed” Naming Convention
In order to have a call to
[UIImage imageNamed: <base name>];
return the right image, the full name of the image files (and the corresponding elements in Xcode’s Project Navigator) should be constructed like this:
<base name><iPhone5 element><Retina element><iPad element>.<image type>
Here are the elements used to construct the complete file names:
- iPhone5 images get a “-568h”
- Retina resolution images get a “@2x”
- iPad images get a “~ipad” (case dependent)
- I found that this works for .PNG images, I couldn’t get it to reliably work for JPG images.
- I’ve heard conflicting information whether you can drop the retina element for an iPhone5 image. Some posts are reasoning that it’s not needed as there is no non-retina iPhone with a 568px height. However, I found it only worked consistently with the “@2x” element.
- This convention does not differentiate between landscape and portrait images. If you want to use different images, you have to use different base names, detect the current orientation and choose the right “class” of images.
Complete File Names for different Devices
Putting these elements together, we get the following file names for the base name AppBg (short for App background):
|iPhone (Non-Retina)||<base name>.png||AppBg.png|
|iPhone (Retina)||<base name>@2x.png||AppBg@2x.png|
So when you are using the method call
[UIImage imageNamed: @"AppBg"]
the result will automatically contain the right image for the device your app is running on.
In addition to using the right image in your code (e.g. for the background image), this name convention also applies to the “Default” image that is used as the “splash screen” when an application starts.