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

How to render a UIView to a UIImage

Written by Paul Hudson    @twostraws

You can render any UIView into a UIImage in just four lines of code, and that even handles drawing all the subviews automatically. Here's the code:

let renderer = UIGraphicsImageRenderer(size: view.bounds.size)
let image = renderer.image { ctx in
    view.drawHierarchy(in: view.bounds, afterScreenUpdates: true)
}

Helpfully, that code works equally well no matter what the view contains - if you're using UIKit, SpriteKit, Metal or whatever, it all works.

Available from iOS 10.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.

Learn Server-Side Swift now!

Take your Swift code to the server and become a full-stack developer with my latest book: Server-Side Swift!

Click here to visit the Hacking with Swift store >>