-1

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.

iYoung
  • 3,596
  • 3
  • 32
  • 59
  • please check [here](https://stackoverflow.com/questions/4334233/how-to-capture-uiview-to-uiimage-without-loss-of-quality-on-retina-display), i think you got the answer. – Bera Bhavin Aug 02 '17 at 14:00
  • Tell us specifically how your code fails to do what you want it to do. What error are you getting, or how is the result not what you want? – Duncan C Aug 02 '17 at 14:16
  • 1
    @DuncanC I have edited my question & added my observation. Let me know if it is still unclear – iYoung Aug 02 '17 at 14:25

1 Answers1

6
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!

M-P
  • 4,909
  • 3
  • 25
  • 31
Mohamad Bachir Sidani
  • 2,077
  • 1
  • 11
  • 17
  • Hi, Thank you for your answer, I had tried that already & just verified it once again & I am getting the same thing with this as well. It is working perfectly fine on simulator but it is returning black image on real device. – iYoung Aug 02 '17 at 15:05
  • If you're getting a black image, you may want to try setting opaque to false: `UIGraphicsBeginImageContextWithOptions(view.bounds.size, false, 0.0)` – OffensivelyBad Feb 26 '18 at 21:34