Skip to content

Instantly share code, notes, and snippets.

@peatiscoding
Created November 7, 2016 14:16
Show Gist options
  • Select an option

  • Save peatiscoding/83852abe8150e66da1b3b4855e8f7b84 to your computer and use it in GitHub Desktop.

Select an option

Save peatiscoding/83852abe8150e66da1b3b4855e8f7b84 to your computer and use it in GitHub Desktop.
An easy way to create a UIImage snapshot from given view.
extension UIView {
func snapshot() -> UIImage {
UIGraphicsBeginImageContextWithOptions(self.bounds.size, true, UIScreen.mainScreen().scale)
self.layer.renderInContext(UIGraphicsGetCurrentContext()!)
let img = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return img
}
}
@peatiscoding

Copy link
Copy Markdown
Author

Simply call:

let image = view.snapshot()

@AmitaiB

AmitaiB commented Jul 27, 2018

Copy link
Copy Markdown

πŸ‘

@blastar

blastar commented Aug 5, 2019

Copy link
Copy Markdown

Swift 5 version:

extension UIView {
    func snapshot() -> UIImage? {
        UIGraphicsBeginImageContextWithOptions(self.bounds.size, true, UIScreen.main.scale)
        self.layer.render(in: UIGraphicsGetCurrentContext()!)
        let img = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return img
    }
}

@Innovatewithapple

Copy link
Copy Markdown

πŸ‘πŸ»

@EvgenyKarkan

EvgenyKarkan commented Nov 23, 2022

Copy link
Copy Markdown

More safe approach (without force unwrap).

extension UIView {

    func snapshot() -> UIImage? {
        UIGraphicsBeginImageContextWithOptions(bounds.size, true, UIScreen.main.scale)

        guard let currentContext = UIGraphicsGetCurrentContext() else {
            UIGraphicsEndImageContext()
            return nil
        }

        layer.render(in: currentContext)

        let image = UIGraphicsGetImageFromCurrentImageContext()

        UIGraphicsEndImageContext()

        return image
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment