我试图在显示 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!
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)