将UIView转换为UIImage Swift 3

iYo*_*ung -1 iphone uiview uiimage ios swift3

我正在努力转换UIView为扩展,UIImage但我面临一个奇怪的问题,我能够在iOS模拟器中获得正确的图像,但我在真实设备中获得黑色图像.以下是我的代码

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!
}
}
Run Code Online (Sandbox Code Playgroud)

任何人都可以解释我做错了什么,我无法在真实设备中获得正确的图像?

编辑

观察:

每当我在模拟器中将UIView传递给此扩展时,我都能获得该视图的完美图像

每当我在实际设备中将UIView传递给此扩展时,我得到的图像完全是黑色而不是UIView中的元素,这与模拟器结果不同.

Moh*_*ani 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
    }
}
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助!