15.4. Drawing Images

Problem

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

Solution

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

Discussion

UIKit helps you draw images with ease. All you have to do is to 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.

Note

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 Xcode (onto the lefthand side, where the rest of your project files are stored).

  3. A new dialog box will appear on the screen. Check the “Copy items into destination ...

Get iOS 5 Programming Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.