---
title: "#73: UIImage Tips 🌄"
url: https://littlebitesofcocoa.com/73-uiimage-tips
author: Jake Marsh
date: 2015-09-02
published: 2015-09-02
topics: ["UIKit"]
description: "UIImage is a deceptively powerful part of UIKit. Let's take a look at some of the different ways we can use it: Let UIKit do the heavy lifting by using..."
---

# #73: UIImage Tips 🌄

By Jake Marsh, September 2, 2015. HTML: https://littlebitesofcocoa.com/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.

``` swift
UIImage(named: "filters-icon")!
  .imageWithRenderingMode(.AlwaysTemplate)
```

<img src="https://media.littlebitesofcocoa.com/bite-assets/073-uiimage-tips-1.png" style="max-width: 123px;" />&nbsp;&nbsp;&nbsp;<img src="https://media.littlebitesofcocoa.com/bite-assets/073-uiimage-tips-2.png" style="max-width: 99px;" />

## Animation

**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**.

``` swift
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.

``` swift
let buttonBGImage = UIImage(named: "button-stretchable")!
  .resizableImageWithCapInsets(UIEdgeInsets(
    top: 4.0,
    left: 4.0,
    bottom: 4.0,
    right: 4.0
  ))
```

<img src="https://media.littlebitesofcocoa.com/bite-assets/073-uiimage-tips-4.png" style="max-width: 99px;" /> <img src="https://media.littlebitesofcocoa.com/bite-assets/073-uiimage-tips-5.png" style="max-width: 99px;" /> <img src="https://media.littlebitesofcocoa.com/bite-assets/073-uiimage-tips-6.png" style="max-width: 139px;" />

## Write JPEG Data to a File

The second parameter controls quality/compression of the JPEG. Smaller numbers result in smaller but uglier image files.

``` swift
let data = UIImageJPEGRepresentation(someImage, 1.0)

data?.writeToFile(imageFilePath, atomically: true)
```
