Screenshot of a view without displaying it

自闭症网瘾萝莉.ら 提交于 2019-12-25 07:40:01

问题


I am trying to take a screenshot of a MySecondViewController.view while MyFirstViewController is displayed. I don't want MySecondViewController to appear on the screen at any moment. Is that possible?

Here is my current code inside a function of 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)
}

Here is the UIView extension I am using:

func snapshot() -> UIImage {
    UIGraphicsBeginImageContextWithOptions(bounds.size, false, UIScreen.main.scale)
    drawHierarchy(in: self.bounds, afterScreenUpdates: true)
    let image = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    return image!
}

With this code, the snapshot variable contains an invisible picture with the good dimensions. I think it is taking the screenshot after the view has been popped out of the navigation controller.

If I try setting the afterScreenUpdates value to false, then the result is the same. Then, I think it is taking the screenshot before the view has been pushed in the navigation controller.


回答1:


I've found what I was looking for.

Here is the new code:

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


来源:https://stackoverflow.com/questions/40893318/screenshot-of-a-view-without-displaying-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!