【问题标题】: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,那么结果是一样的。然后,我认为它是在视图被推送到导航控制器之前截取屏幕截图。

【问题讨论】:

    标签: swift uiview screenshot


    【解决方案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!
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-16
      相关资源
      最近更新 更多