20.4. Drawing Images


You want to be able to draw images on the screen of an iOS device.


Use the UIImage class to load an image and then use the drawInRect: method of the image to draw it on a graphics context.


UIKit helps you draw images with ease. All you have to do is load your images in instances of type UIImage. The UIImage class provides various class and instance methods to load your images. Here are some of the important ones in iOS:

imageNamed: class method

Loads the image (and caches the image if it can load it properly). The parameter to this method is the name of the image in the bundle, such as Tree Texture.png.

imageWithData: class method

Loads an image from the data encapsulated in an instance of an NSData object that was passed as the parameter to this method.

initWithContentsOfFile: instance method (for initialization)

Uses the given parameter as the path to an image that has to be loaded and used to initialize the image object.


This path should be the full path to the image in the app bundle.

initWithData: instance method (for initialization)

Uses the given parameter of type NSData to initialize the image. This data should belong to a valid image.

Please follow these steps to add an image to your Xcode project:

  1. Find where the image is located in your computer.

  2. Drag and drop the image into your image category, usually named images.xcassets. Xcode will do the rest for you.


You can retrieve Xcode’s icon by following these steps:

  1. Find the Xcode app ...

Get iOS 7 Programming Cookbook now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.