Swift 未显示视图的屏幕截图

Swift 未显示视图的屏幕截图,swift,uiview,screenshot,Swift,Uiview,Screenshot,我正在尝试在显示MyFirstViewController时拍摄MySecondViewController.view的屏幕截图。我不希望MySecondViewController随时出现在屏幕上。 可能吗 以下是MyFirstViewController函数中的当前代码: func createPreview() { let mySecondViewController = self.storyboard!.instantiateViewController(withIdentifi

我正在尝试在显示MyFirstViewController时拍摄MySecondViewController.view的屏幕截图。我不希望MySecondViewController随时出现在屏幕上。 可能吗

以下是MyFirstViewController函数中的当前代码:

func createPreview() {
    let mySecondViewController = self.storyboard!.instantiateViewController(withIdentifier: "MySecondViewController")
    self.navigationController?.pushViewController(mySecondViewController, animated: false)
    let snapshot = mySecondViewController.view.snapshot()
    self.navigationController?.popViewController(animated: false)
}
以下是我正在使用的UIView扩展:

func snapshot() -> UIImage {
    UIGraphicsBeginImageContextWithOptions(bounds.size, false, UIScreen.main.scale)
    drawHierarchy(in: self.bounds, afterScreenUpdates: true)
    let image = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    return image!
}
使用此代码,
snapshot
变量包含一个尺寸良好的不可见图片。我认为这是在视图从导航控制器弹出后拍摄的屏幕截图


如果我尝试将
afterScreenUpdates
值设置为false,则结果相同。然后,我认为它是在视图被推入导航控制器之前拍摄的屏幕截图。

我找到了我要找的内容

以下是新代码:

func createPreview() {
    let mySecondViewController = self.storyboard!.instantiateViewController(withIdentifier: "MySecondViewController")
    let snapshot = mySecondViewController.view.snapshot()
}

extension UIView {
    func snapshot() -> UIImage {
        UIGraphicsBeginImageContextWithOptions(bounds.size, self.isOpaque, UIScreen.main.scale)
        layer.render(in: UIGraphicsGetCurrentContext()!)
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return image!
    }
}