未显示的视图的屏幕截图 [英] Screenshot of a view without displaying it
问题描述
我正在尝试在显示 MyFirstViewController 时截取 MySecondViewController.view 的屏幕截图.我不希望 MySecondViewController 随时出现在屏幕上.这可能吗?
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?
这是我当前在 MyFirstViewController 函数中的代码:
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)
}
这是我正在使用的 UIView 扩展:
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!
}
使用此代码,snapshot
变量包含具有良好尺寸的不可见图片.我认为它是在视图从导航控制器中弹出后截取屏幕截图.
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.
如果我尝试将 afterScreenUpdates
值设置为 false,那么结果是相同的.然后,我认为它是在导航控制器中推送视图之前截取屏幕截图.
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.
推荐答案
我找到了我要找的东西.
I've found what I was looking for.
这是新代码:
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!
}
}
这篇关于未显示的视图的屏幕截图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!