简体   繁体   中英

Convert UIView to UIImage Swift 3

I am working on an extension to convert UIView to UIImage but I am having facing a strange issue that I am able to get correct image in iOS Simulator but I am getting black image in real device. Below is my code

extension UIView {
func screenshotImage() -> UIImage {
    UIGraphicsBeginImageContextWithOptions(self.bounds.size, false, 0.0);
    self.drawHierarchy(in: self.bounds, afterScreenUpdates: true)
    let screenShot = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return screenShot!
}
}

Can anyone explain what am I doing wrong that I am not able to get correct image in real device?

EDIT

Observations:

Whenever I pass a UIView to this extension in simulator I get perfect image of that view

Whenever I pass a UIView to this extension in real device I get an image which is completely black instead of elements in that UIView unlike to simulator result.

extension UIImage {
    class func imageWithView(view: UIView) -> UIImage? {
        UIGraphicsBeginImageContextWithOptions(view.bounds.size, view.isOpaque, 0.0)
        view.drawHierarchy(in: view.bounds, afterScreenUpdates: true)
        let img = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return img
    }
}

Hope this helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM