【问题标题】:Unable to get a screenshot on iOS using the snapshotViewAfterScreenUpdates: method of UIScreen无法在 iOS 上使用 snapshotViewAfterScreenUpdates 获取屏幕截图:UIScreen 的方法
【发布时间】:2018-08-10 09:50:51
【问题描述】:

我正在尝试在我的 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() 方法返回的截图视图中提取图像?

【问题讨论】:

  • 添加断点,保存前检查图像
  • @CZ54:我试过了,发现图片大小正确,确实是空白的。
  • 用 let deadlineTime = DispatchTime.now() + .seconds(1) DispatchQueue.main.asyncAfter(deadline:deadlineTime) { } 替换定时器

标签: ios swift screenshot uiscreen


【解决方案1】:

斯威夫特 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)
    }

【讨论】:

  • 感谢您的回答。不幸的是,虽然self.view?.drawHierarchy() 确实生成了一个图像,但这种方法对我不起作用,因为生成的图像不包含状态栏。这就是我需要调用UIScreen.main.snapshotView() 的原因,因为它生成的屏幕截图视图包含状态栏。这里的关键问题是如何从屏幕截图视图中提取图像。
猜你喜欢
  • 2013-11-16
  • 2020-03-19
  • 1970-01-01
  • 1970-01-01
  • 2019-12-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-13
相关资源
最近更新 更多