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 methodLoads 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 methodLoads 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:
Find where the image is located in your computer.
Drag and drop the image into Xcode (onto the lefthand side, where the rest of your project files are stored).
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.