An object that manages image data in your app.


class UIImage : NSObject


You use image objects to represent image data of all kinds, and the UIImage class is capable of managing data for all image formats supported by the underlying platform. Image objects are immutable, so you always create them from existing image data, such as an image file on disk or programmatically created image data. An image object may contain a single image or a sequence of images you intend to use in an animation.

You can use image objects in several different ways:

  • Assign an image to a UIImageView object to display the image in your interface.

  • Use an image to customize system controls such as buttons, sliders, and segmented controls.

  • Draw an image directly into a view or other graphics context.

  • Pass an image to other APIs that might require image data.

Although image objects support all platform-native image formats, it is recommended that you use PNG or JPEG files for most images in your app. Image objects are optimized for reading and displaying both formats, and those formats offer better performance than most other image formats. Because the PNG format is lossless, it is especially recommended for the images you use in your app’s interface.

Creating Image Objects

When creating image objects using the methods of this class, you must have existing image data located in a file or data structure. You cannot create an empty image and draw content into it. There are many options for creating image objects, each of which is best for specific situations:

  • Use the init(named:in:compatibleWith:) method (or the init(named:) method) to create an image from an image asset or image file located in your app’s main bundle (or some other known bundle). Because these methods cache the image data automatically, they are especially recommended for images that you use frequently.

  • Use the imageWithContentsOfFile: or init(contentsOfFile:) method to create an image object where the initial data is not in a bundle. These methods load the image data from disk each time, so you should not use them to load the same image repeatedly.

  • Use the animatedImage(with:duration:) and animatedImageNamed(_:duration:) methods to create a single UIImage object comprised of multiple sequential images. Install the resulting image in a UIImageView object to create animations in your interface.

Other methods of the UIImage class let you create animations from specific types of data, such as Core Graphics images or image data that you create yourself. UIKit also provides the UIGraphicsGetImageFromCurrentImageContext() function for creating images from content that you draw yourself. You use that function in conjunction with a bitmap-based graphics context, which you use to capture your drawing commands.

Image assets are the easiest way to manage the images that ship with your app. Each new Xcode project contains an assets library, to which you can add multiple image sets. An image set contains the variations of a single image that your app uses. A single image set can provide different versions of an image for different platforms, for different trait environments (compact or regular), and for different scale factors.

In addition to loading images from disk, you can ask the user to supply images from an available camera or photo library using a UIImagePickerController object. An image picker displays a custom user interface for selecting images. Accessing user-supplied images requires explicit user permission. For more information about using an image picker, see UIImagePickerController.

Defining a Stretchable Image

A stretchable image is one that defines regions where the underlying image data can be duplicated in an aesthetically pleasing way. Stretchable images are commonly used to create backgrounds that can grow or shrink to fill the available space.

You define a stretchable image by adding insets to an existing image using the resizableImage(withCapInsets:) or resizableImage(withCapInsets:resizingMode:) method. The insets subdivide the image into two or more parts. Specifying nonzero values for each inset yields an image divided into nine parts, as shown in Figure 1.

Figure 1

Using insets to define stretchable regions

Each inset defines the portion of the image that does not stretch in the given dimension. The regions inside an image’s top and bottom insets maintain a fixed height, and the areas inside the left and right insets maintain a fixed width. Figure 2 shows how each part of a nine-part image stretches as the image itself is stretched to fill the available space. The corners of the image do not change size because they are inside both a horizontal and vertical inset.

Figure 2

Stretchable portions of a nine-part image

Comparing Images

The isEqual(_:) method is the only reliable way to determine whether two images contain the same image data. The image objects you create may be different from each other, even when you initialize them with the same cached image data. The only way to determine their equality is to use the isEqual(_:) method, which compares the actual image data. Listing 1 illustrates the correct and incorrect ways to compare images.

Listing 1

Comparing two images

let image1 = UIImage(named: "MyImage")
let image2 = UIImage(named: "MyImage") 
if image1 != nil && image1!.isEqual(image2) {
    // Correct. This technique compares the image data correctly.
if image1 == image2 {
    // Incorrect! Direct object comparisons may not work.

Accessing the Image Data

Image objects not provide direct access to their underlying image data. However, you can retrieve the image data in other formats for use in your app. Specifically, you can use the cgImage and ciImage properties to retrieve versions of the image that are compatible with Core Graphics and Core Image, respectively. You can also use the pngData() and jpegData(compressionQuality:) functions to generate an NSData object containing the image data in either the PNG or JPEG format.


Loading and Caching Images

init?(named: String, in: Bundle?, compatibleWith: UITraitCollection?)

Returns the named image that is also compatible with the specified trait collection.

init?(named: String)

Returns the image object associated with the specified filename.

init(imageLiteralResourceName: String)

Returns the image object associated with the specified resource.

Creating and Initializing Image Objects

init?(contentsOfFile: String)

Initializes and returns the image object with the contents of the specified file.

init?(data: Data)

Initializes and returns the image object with the specified data.

init?(data: Data, scale: CGFloat)

Initializes and returns the image object with the specified data and scale factor.

init(cgImage: CGImage)

Initializes and returns the image object with the specified Quartz image reference.

init(cgImage: CGImage, scale: CGFloat, orientation: UIImage.Orientation)

Initializes and returns an image object with the specified scale and orientation factors

init(ciImage: CIImage)

Initializes and returns an image object with the specified Core Image object.

init(ciImage: CIImage, scale: CGFloat, orientation: UIImage.Orientation)

Initializes and returns an image object with the specified Core Image object and properties.

Creating Specialized Image Objects

class func animatedImage(with: [UIImage], duration: TimeInterval) -> UIImage?

Creates and returns an animated image from an existing set of images.

func imageFlippedForRightToLeftLayoutDirection() -> UIImage

Returns the current image, prepared to flip horizontally when it’s in a right-to-left layout.

func withHorizontallyFlippedOrientation() -> UIImage

Returns a version of the image whose image orientation is the mirror of the original image.

func withRenderingMode(UIImage.RenderingMode) -> UIImage

Creates and returns a new image object with the specified rendering mode.

func withAlignmentRectInsets(UIEdgeInsets) -> UIImage

Returns a new version of the image that uses the specified alignment insets.

func resizableImage(withCapInsets: UIEdgeInsets) -> UIImage

Creates and returns a new image object with the specified cap insets.

func resizableImage(withCapInsets: UIEdgeInsets, resizingMode: UIImage.ResizingMode) -> UIImage

Creates and returns a new image object with the specified cap insets and options.

Getting the Image Data

var cgImage: CGImage?

The underlying Quartz image data.

var ciImage: CIImage?

The underlying Core Image data.

var images: [UIImage]?

For an animated image, this property holds the complete array of UIImage objects that make up the animation.

var imageAsset: UIImageAsset?

Returns a reference to the image asset (if any) associated with the image.

Getting the Image Size and Scale

var scale: CGFloat

The scale factor of the image.

var size: CGSize

The logical dimensions of the image, measured in points.

Image Attributes

var imageOrientation: UIImage.Orientation

The orientation of the receiver’s image.

enum UIImage.Orientation

A value describing the intended display orientation for an image.

var flipsForRightToLeftLayoutDirection: Bool

A Boolean value that indicates whether the image should flip in a right-to-left layout.

var resizingMode: UIImage.ResizingMode

The resizing mode of the image.

enum UIImage.ResizingMode

Specifies the possible resizing modes for an image.

var duration: TimeInterval

Returns the time interval used to display an animated image.

var capInsets: UIEdgeInsets

The end-cap insets.

var alignmentRectInsets: UIEdgeInsets

The alignment metadata used to position the image during layout.

var traitCollection: UITraitCollection

Returns the trait collection that describes the image.

Getting Rendering Information

var renderingMode: UIImage.RenderingMode

Determines how an image is rendered.

enum UIImage.RenderingMode

Specifies the possible rendering modes for an image.

var imageRendererFormat: UIGraphicsImageRendererFormat

The image renderer format that is best suited for the image.

Drawing Images

func draw(at: CGPoint)

Draws the image at the specified point in the current context.

func draw(at: CGPoint, blendMode: CGBlendMode, alpha: CGFloat)

Draws the entire image at the specified point using the custom compositing options.

func draw(in: CGRect)

Draws the entire image in the specified rectangle, scaling it as needed to fit.

func draw(in: CGRect, blendMode: CGBlendMode, alpha: CGFloat)

Draws the entire image in the specified rectangle and using the specified compositing options.

func drawAsPattern(in: CGRect)

Draws a tiled Quartz pattern using the receiver’s contents as the tile pattern.


func stretchableImage(withLeftCapWidth: Int, topCapHeight: Int) -> UIImage

Creates and returns a new image object with the specified cap values.

var leftCapWidth: Int

The horizontal end-cap size.

var topCapHeight: Int

The vertical end-cap size.


Instance Methods

func jpegData(compressionQuality: CGFloat) -> Data?

Returns the data for the specified image in JPEG format.

func pngData() -> Data?

Returns the data for the specified image in PNG format