ios - 无法使用 snapshotViewAfterScreenUpdates 在 iOS 上获取屏幕截图 : method of UIScreen

标签 ios swift screenshot uiscreen

我正在尝试在我的 iOS 应用程序中获取屏幕截图图像。屏幕截图必须包含屏幕上的所有内容,包括状态栏,因此 this 等解决方案对我不起作用。我尝试了以下方法:

override func viewDidLoad() {
    super.viewDidLoad()

    // Wait for one second before taking the screenshot.
    Timer.scheduledTimer(withTimeInterval: 1, repeats: false) { timer in
        // Get a view containing the screenshot, shrink it a little, and show it.
        let view = UIScreen.main.snapshotView(afterScreenUpdates: false)
        view.frame = view.frame.insetBy(dx: 18, dy: 32)
        self.view.addSubview(view)

        // Get the screenshot image from the view, and save it to the photos album.
        UIGraphicsBeginImageContextWithOptions(UIScreen.main.bounds.size, false, 0)
        view.drawHierarchy(in: view.bounds, afterScreenUpdates: true)
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        UIImageWriteToSavedPhotosAlbum(image!, nil, nil, nil)
    }
}

我在 iPhone 6 Plus 的 iOS 11.4.1 中运行了以上代码。截屏成功并显示在屏幕上,但保存到相册的图像是一片空白。我究竟做错了什么?捕获完整屏幕截图的正确方法是什么?

更新

根据 CZ54 的建议,我在调试 session 中检查了变量 image 的值,发现它完全是空白的,尽管它的大小是正确的。所以这里的关键问题是,我应该如何从 UIScreen.main.snapshotView() 方法返回的屏幕截图 View 中提取图像?

最佳答案

swift 4.1.1

   let deadlineTime = DispatchTime.now() + .seconds(1)
    // Wait for one second before taking the screenshot.
    DispatchQueue.main.asyncAfter(deadline: deadlineTime) {

        let view = UIScreen.main.snapshotView(afterScreenUpdates: false)
        view.frame = view.frame.insetBy(dx: 18, dy: 32)
        self.view.addSubview(view)

        // Get a view containing the screenshot, shrink it a little, and show it.
        UIGraphicsBeginImageContextWithOptions(self.view.frame.size, true, UIScreen.main.scale)
        //guard let context = UIGraphicsGetCurrentContext() else { return }
        //self.view.layer.render(in: context)
        self.view?.drawHierarchy(in:  self.view.bounds, afterScreenUpdates: true)
        guard let image = UIGraphicsGetImageFromCurrentImageContext() else { return }
        UIGraphicsEndImageContext()

        //Save it to the camera roll
        UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil)
    }

关于ios - 无法使用 snapshotViewAfterScreenUpdates 在 iOS 上获取屏幕截图 : method of UIScreen,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51783766/

相关文章:

iphone - iOS 5 : Data encryption AES-256 EncryptWithKey: not found

ios - 如何在 XCode Interface Builder 中设置 UIButton 的选定图像

ios - UITextView InputView UITableViewController

fonts - 如何在 Cypress 中处理字体加载和屏幕截图

c# - 如何知道用户是否进行了屏幕截图?

ios - 刷新控制(拉动刷新)滞后?

ios - 通过参数判断子类类型,报错 "Use of undeclared type "。我能怎么做?

ios - 从 UITapGestureRecognizer 访问 subview

swift - 如何在 Swift 中使用 Alamofireimage 在 Collection View 中下载图像并保持单元格中的图像高度?

android - Eclipse 和自动截图