gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:02:00 45 4
gpt4 key购买 nike

我正在尝试在我的 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/

45 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com