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
}
}
@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