我正在尝试在显示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,则结果相同。然后,我认为它是在视图被推入导航控制器之前截取屏幕截图。
答案 0 :(得分:2)
我找到了我要找的东西。
这是新代码:
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!
}
}