【发布时间】: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