Want to offer native, in-app customer service to your users? Get going quickly with Zendesk’s Mobile SDKs. Free with Zendesk.


#73: UIImage Tips πŸŒ„


UIImage is a deceptively powerful part of UIKit. Let's take a look at some of the different ways we can use it:

Template Images

Let UIKit do the heavy lifting by using template images. UIKit only looks at the alpha channel, and draws the image using the tint color of the view it's contained in.

UIImage(named: "filters-icon")!



UIImages can be animated. A UIImage can contain many images within it, as well as a duration. Put the containing image in a UIImageView and call startAnimating to see it.

Pattern Images

This one's fun. We can create a UIColor from a UIImage. The resulting "color" will be our image, tiled. We can then use this UIColor as a background color of a view.

UIColor(patternImage: UIImage("bg-pattern")!)

Stretchable Images

Sometimes we don't want to write a bunch of Core Graphics code to implement things like rounded corners, inner shadows, etc. UIImage has a great feature for implementing resizable (also sometimes called 9-patch) images.

We want to implement a fancy button. All we need is a tiny little 9x9 image. In code, we'll tell UIKit to load the image, and create a resizable image from it.

let buttonBGImage = UIImage(named: "button-stretchable")!
    top: 4.0,
    left: 4.0,
    bottom: 4.0,
    right: 4.0

Write JPEG Data to a File

The second parameter controls quality/compression of the JPEG. Smaller numbers result in smaller but uglier image files.

let data = UIImageJPEGRepresentation(someImage, 1.0)

data?.writeToFile(imageFilePath, atomically: true)