无法使用UIScreen的snapshotViewAfterScreenUpdates:方法在iOS上获取屏幕截图

时间:2018-08-10 09:50:51

标签: 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的建议,我在调试会话中检查了变量image的值,发现它的大小完全正确,但完全空白。所以这里的关键问题是,我应该如何从UIScreen.main.snapshotView()方法返回的屏幕快照视图中提取图像?

1 个答案:

答案 0 :(得分:0)

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)
    }