不显示视图的屏幕截图

Posted

技术标签:

【中文标题】不显示视图的屏幕截图【英文标题】:Screenshot of a view without displaying it 【发布时间】:2016-11-30 16:25:33 【问题描述】:

我正在尝试在显示 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,那么结果是一样的。然后,我认为它是在视图被推送到导航控制器之前截取屏幕截图。

【问题讨论】:

【参考方案1】:

我找到了我要找的东西。

这是新代码:

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!
    

【讨论】:

以上是关于不显示视图的屏幕截图的主要内容,如果未能解决你的问题,请参考以下文章