NEW: Master Swift design patterns with my latest book! >>

How to make resizable images using resizableImage(withCapInsets:)

Written by Paul Hudson    @twostraws

If you use a small image in a large image view, you can make the image stretch to fit if you want to but it probably won't look great. iOS provides an alternative known as resizable images, which is where you define part of an image as being fixed in size and let iOS stretch the remainder.

This technique is common with button graphics: you make the corners fixed in size, then stretch the center part as big as it needs to be. The center part ought to be just one pixel by one pixel in size so that it stretches perfectly, but you can also ask iOS to repeat the center area as a tile if that's what you want.

This example code below creates a resizable image by defining the corners as 8 points each and stretching the rest:

if let img = UIImage(named: "button") {
    let resizable = img.resizableImage(withCapInsets: UIEdgeInsets(top: 8, left: 8, bottom: 8, right: 8), resizingMode: .stretch)
}

Available from iOS 2.0

Did this solution work for you? Please pass it on!

Other people are reading…

About the Swift Knowledge Base

This is part of the Swift Knowledge Base, a free, searchable collection of solutions for common iOS questions.

Get six books for only $150

The Swift Power Pack includes my first six books for one low price, helping you jumpstart a new career in iOS development – check it out!

Click here to visit the Hacking with Swift store >>