Last active
July 2, 2024 14:55
-
-
Save stakes/de024878ce3cc43d7ee6 to your computer and use it in GitHub Desktop.
UIImage from UIView extension
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} | |
} |
//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)
}
import UIKit
extension UIView {
func asImage() -> UIImage {
let renderer = UIGraphicsImageRenderer(size: frame.size)
return renderer.image { context in
layer.render(in: context.cgContext)
}
}
}
@leoniralves Thank You!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
iOS10 Swift3 version