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 ...

Get Swift iOS 24-Hour Trainer 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.