Lesson 13

Adding Images to Your View

The UIKit framework provides classes that enable you to represent and display images. In this lesson, you learn how to use the UIImage and UIImageView classes.

The UIImage Class

A UIImage object represents image data that has either been read from a file or created using Quartz primitives. Instances are immutable. Thus, their properties can't be changed once they have been created. UIImage instances do not provide access to the underlying image data, but do enable you to retrieve a PNG or JPEG image representation in an NSData object.

Images generally require large amounts of memory to store, and you should avoid creating image objects larger than 4096 x 4096 pixels. To load an image from a file into a UIImage object, you first need to ensure the file is in one of the formats listed in Table 13.1.

Table 13.1 UIImage Supported File Formats

Description File Extensions
Portable Network Graphics .png
Joint Photographic Experts Group .jpeg, .jpg
Graphics Interchange Format .gif
Windows Device Independent Bitmap .bmp
Tagged Image File Format .tif, .tiff

You also need to ensure that the file is part of the project's asset catalog. To access the asset catalog for your project, simply click on the Assets.xcassets file in the Project Explorer (see Figure 13.1).

Screenshot of Project Explorer window and Assets.xcassets file under TreasureHunt is selected and appicon is highlighted with Appicon screen with asset catalog.

Figure 13.1

An asset catalog lets you keep all the images in your project in one place and access them conveniently. An asset catalog can contain the following:

Each image set in an asset catalog has a unique name that can be used to refer to the asset from both the Interface editor and code. To add a new image set to an asset catalog, select Editor arrow New Image Set. Double-click the new image set entry within the asset catalog to rename it.

For any given image set, you must provide at least one image. It is highly recommended that you provide multiple versions at different sizes. When you create a new image asset, you can provide three sizes of the image (see Figure 13.2).

Screenshot of Project Explorer window with Assets.xcassets file selected, Images grayed and the Image options 1x,2x,3x, and Universal.

Figure 13.2

The base version of the image is called the 1x version, and is used when your app is running on a non-retina device. The only non-retina devices that are supported under iOS9 are the early generation iPads. To support retina devices, you provide an image that is twice the size of the base (non-retina) version. This larger image is called the 2x version. When the iPhone 6Plus was introduced with its larger screen size, a third larger image size was introduced into the mix to support this device. This larger image size, which is only used with the iPhone 6 Plus, is called the 3x version and is three times as large as the base 1x version.

Alternately, you can provide device-specific sizes by selecting Device Specific in the Devices drop-down of the Attribute Editor (see Figure 13.3).

Screenshot of Project Explorer window with Assets.xcassets file selected and iPhone and iPad are featured in the Images tab by selecting Device Specific in the Devices drop-down of the Attribute Editor.

Figure 13.3

If you have an image set called cat and want to load it into a UIImage object, you use the following code:

let catImage:UIImage! = UIImage(named: "cat")

This code uses one of the constructors of the UIImage class, which in turn implements an internal system cache. Thus, if you were to use this method to repeatedly load the same image file, the image data would be loaded only once and shared between the UIImage instances.

Loading images from your application bundle is not the only way to use UIImage objects. You can also create one from an online data source by downloading the data available at the URL into an NSData object and then instantiating a UIImage using an overloaded constructor that takes an NSData variable as input.

The following code snippet shows how to do this synchronously, but in production code, you should try and download any data from the web, including images, asynchronously. Downloading images asynchronously is an advanced topic and is not covered in this book.

let url = NSURL(string:"http://…")
let data = NSData(contentsOfURL: url!)
let image:UIImage! = UIImage(data: data!)

The UIImageView Class

A UIImageView object provides a container for displaying either a single UIImage object or an animated series of UIImage objects. To add a UIImageView object to a view controller or storyboard scene, simply drag an Image View object from the Object library (see Figure 13.4).

Screenshot of a scene from a storyboard with Image View in the canvas and Image View object selected in the Object Library.

Figure 13.4

To set up the default image displayed in the image view, simply select an image from the project's asset catalog for the image property in the Attribute inspector (see Figure 13.5).

Screenshot of Attribute Inspector dialog box and Image option under Image View tab has apple, banana, background, and orange as options.

Figure 13.5

If you wish to display a UIImage object in an image view programmatically, you need to create an outlet for the image view in the view controller class and set up its image property as follows:

imageView.image = UIImage(named: "cat")

To use a UIImageView object to perform simple frame animation, simply provide an array of UIImage objects in the image view's animationImages property as follows:

let animationImageList:[AnyObject] = [
    UIImage(named: "frame1")!,
    UIImage(named: "frame2")!,
    UIImage(named: "frame3")!,
    UIImage(named: "frame4")!
]
imageView.animationImages = animationImageList

To kick off the animation, call the startAnimating method of the image view:

imageView.startAnimating()

Specify the duration of the animation in seconds, using the animationDuration property:

imageView.animationDuration = 2

Try It

In this Try It, you create a new Xcode project based on the Single View Application template called TreasureHunt that displays an image and asks the user to find an object in the image. When the user taps the object, a short congratulatory animation sequence is displayed.

Lesson Requirements

  • Launch Xcode.
  • Create a new project based on the Single View Application template.
  • Edit the storyboard with Interface editor.
  • Import image resources into the project.
  • Add a UILabel instance to the default scene.
  • Add two UIImageView instances to the default scene.
  • Use a gesture recognizer to detect a tap on the image and display an alert view.
  • If the tap occurs over a specific region of the image, display a congratulatory frame animation.

Hints

  • To show the Object library, select View arrow Utilities arrow Show Object Library.
  • To show the assistant editor, select View arrow Assistant Editor arrow Show Assistant Editor.

Step-by-Step