The UIKit framework provides classes that enable you to represent and display images. In this lesson, you learn how to use the
and UIImage
classes.UIImageView
A
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 UIImage
object.NSData
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
object, you first need to ensure the file is in one of the formats listed in Table 13.1.UIImage
Table 13.1 UIImage Supported File Formats
Description | File Extensions |
Portable Network Graphics |
|
Joint Photographic Experts Group | ,
|
Graphics Interchange Format |
|
Windows Device Independent Bitmap |
|
Tagged Image File Format | ,
|
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
file in the Project Explorer (see Figure 13.1).Assets.xcassets
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 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).
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).
If you have an image set called
and want to load it into a cat
object, you use the following code:UIImage
let catImage:UIImage! = UIImage(named: "cat")
This code uses one of the constructors of the
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.UIImage
Loading images from your application bundle is not the only way to use
objects. You can also create one from an online data source by downloading the data available at the URL into an UIImage
object and then instantiating a NSData
using an overloaded constructor that takes an UIImage
variable as input.NSData
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!)
A
object provides a container for displaying either a single UIImageView
object or an animated series of UIImage
objects. To add a UIImage
object to a view controller or storyboard scene, simply drag an Image View object from the Object library (see Figure 13.4).UIImageView
To set up the default image displayed in the image view, simply select an image from the project's asset catalog for the
property in the Attribute inspector (see Figure 13.5).image
If you wish to display a
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 UIImage
property as follows:image
imageView.image = UIImage(named: "cat")
To use a
object to perform simple frame animation, simply provide an array of UIImageView
objects in the image view's UIImage
property as follows:animationImages
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
method of the image view:startAnimating
imageView.startAnimating()
Specify the duration of the animation in seconds, using the
property:animationDuration
imageView.animationDuration = 2
In this Try It, you create a new Xcode project based on the Single View Application template called
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.TreasureHunt
UILabel
instance to the default scene.UIImageView
instances to the default scene.TreasureHunt
.
Assets.xcassets
file by clicking on it in the project navigator.Images
folder in this chapter's resources from the website.beads
.beads1x.png
, beads2x.png
, and beads3x.png
images from this chapter's resources into the appropriate placeholders in the image set.animframe1
.animframe1_1x.png
, animframe1_2x.png
, and animframe1_3x.png
images from this chapter's resources into the appropriate placeholders in the image set.animframe2
, animframe3
, animframe4
, animframe5
, and animframe6
, and use the appropriate images from this chapter's resources folder.UILabel
instance to the default scene.
MainStoryboard.storyboard
file in Interface Builder.Tap the blue bead!
To show the Attribute inspector, select View Utilities Show Attributes Inspector.UIImageView
instances to the default scene.
bead
. To show the Attribute inspector, select View Utilities Show Attributes Inspector.largeImage
and connect the image view to it.animframe1
. To show the Attribute inspector, select View Utilities Show Attributes Inspector.animatedImage
and connect the image view to it.viewDidLoad
method of the view controller class to resemble the following:override func viewDidLoad() {
super.viewDidLoad()
// install tap gestue recognizer.
let tapRecognizer = UITapGestureRecognizer(target: self,
action:"handleTap:")
tapRecognizer.cancelsTouchesInView = false
self.view.addGestureRecognizer(tapRecognizer)
// setup animatedImage
let frameArray:[UIImage] = [
UIImage(named: "animframe1")!,
UIImage(named: "animframe2")!,
UIImage(named: "animframe3")!,
UIImage(named: "animframe4")!,
UIImage(named: "animframe5")!,
UIImage(named: "animframe6")!
]
animatedImage.animationImages = frameArray
animatedImage.animationDuration = 0.5
animatedImage.animationRepeatCount = 1
animatedImage.userInteractionEnabled = false
animatedImage.hidden = true
}
ViewController.swift
file:func handleTap(sender:UITapGestureRecognizer) {
let startLocation:CGPoint =
sender.locationInView(self.largeImage)
let scaleFactor = self.largeImage.frame.size.height / 430.0;
if ((startLocation.y >= 211 * scaleFactor) &&
(startLocation.y <= (211 + 104) * scaleFactor))
{
animatedImage.hidden = false
animatedImage.startAnimating()
}
}
Test your app in the iOS Simulator.
Click the Run button in the Xcode toolbar. Alternatively, you can select Project Run.