Skip to content

Instantly share code, notes, and snippets.

@stakes
Last active July 2, 2024 14:55
Show Gist options
  • Save stakes/de024878ce3cc43d7ee6 to your computer and use it in GitHub Desktop.
Save stakes/de024878ce3cc43d7ee6 to your computer and use it in GitHub Desktop.
UIImage from UIView extension
import UIKit
extension UIView {
func createImage() -> UIImage {
let rect: CGRect = self.frame
UIGraphicsBeginImageContext(rect.size)
let context: CGContextRef = UIGraphicsGetCurrentContext()
self.layer.renderInContext(context)
let img = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return img
}
}
@DisappearPing
Copy link

DisappearPing commented May 23, 2017

iOS10 Swift3 version

  if #available(iOS 10.0, *) {
            let renderer = UIGraphicsImageRenderer(bounds: bounds)
            return renderer.image { rendererContext in
                layer.render(in: rendererContext.cgContext)
            }
        } else {
            // Fallback on earlier versions
            let rect: CGRect = self.frame
            
            UIGraphicsBeginImageContext(rect.size)
            let context: CGContext = UIGraphicsGetCurrentContext()!
            self.layer.render(in: context)
            let img = UIGraphicsGetImageFromCurrentImageContext()
            UIGraphicsEndImageContext()
            
            return img!
        }

@oitan
Copy link

oitan commented May 2, 2018

//taken from: https://www.hackingwithswift.com/example-code/media/how-to-render-a-uiview-to-a-uiimage
//Available from iOS 10.0
let renderer = UIGraphicsImageRenderer(size: view.bounds.size)
let image = renderer.image { ctx in
view.drawHierarchy(in: view.bounds, afterScreenUpdates: true)
}

@leoniralves
Copy link

import UIKit
extension UIView { 
   func asImage() -> UIImage {
        let renderer = UIGraphicsImageRenderer(size: frame.size)
        return renderer.image { context in
            layer.render(in: context.cgContext)
        }
    }
}

@milczi
Copy link

milczi commented Mar 9, 2022

@leoniralves Thank You!

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