ios - 如何在后台线程上截取 UIView 的屏幕截图?
问题描述
我正在开发的应用程序几乎每个屏幕上都有谷歌地图。为了节省内存,我到处重复使用相同的谷歌地图视图。问题是,当您弹出一个 viewController 时,您可以看到地图所在的空白区域。为了解决这个问题,我在删除地图之前对其进行截图并添加为背景。但还有一个问题,在 iPhoneX 上截屏大约需要 0.3 秒(我想在旧手机上更糟)。有没有办法在后台线程上截取 UIView 的屏幕截图?
解决方案
我使用 swift 尝试了所有最新的快照方法。其他方法在后台对我不起作用。但是以这种方式拍摄快照对我有用。
使用参数视图层和视图边界创建扩展。
extension UIView {
func asImageBackground(viewLayer: CALayer, viewBounds: CGRect) -> UIImage {
if #available(iOS 10.0, *) {
let renderer = UIGraphicsImageRenderer(bounds: viewBounds)
return renderer.image { rendererContext in
viewLayer.render(in: rendererContext.cgContext)
}
} else {
UIGraphicsBeginImageContext(viewBounds.size)
viewLayer.render(in:UIGraphicsGetCurrentContext()!)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return UIImage(cgImage: image!.cgImage!)
}
}
}
用法
DispatchQueue.main.async {
let layer = self.selectedView.layer
let bounds = self.selectedView.bounds
DispatchQueue.global(qos: .background).async {
let image = self.selectedView.asImageBackground(viewLayer: layer, viewBounds: bounds)
}
}
We need to calculate layer and bounds in the main thread, then other operations will work in the background thread. It will give smooth user experience without any lag or interruption in UI.
推荐阅读
- reactjs - webpack错误404但页面加载成功
- php - 通过关系做订单
- spring-boot - 使用 zip 和 last(默认值)的 EmitterProcessor 永远不会发出值
- android - Parceable 错误:在偏移量 1112 处解组未知类型代码 7274595
- angular - 为什么不能在 Angular 中“覆盖”FormGroup?
- javascript - 是否可以从 Chrome/Safari 中的 js 强制刷新页面?(需要 PWA 更新)
- python - TensorFlow 机器学习 - 对用户输入进行预测
- react-native - APNS 错误传输到设备 XXXXXXXXXXXXXX,状态为 400,原因为 BadDeviceToken
- css - Django/BooleanField:如何在案例和标签之间添加空格?
- visual-studio - 如何修复由 Visual Studio 默认项目模板创建的配置错误的 web.config