首页 > 解决方案 > 如何在后台线程上截取 UIView 的屏幕截图?

问题描述

我正在开发的应用程序几乎每个屏幕上都有谷歌地图。为了节省内存,我到处重复使用相同的谷歌地图视图。问题是,当您弹出一个 viewController 时,您可以看到地图所在的空白区域。为了解决这个问题,我在删除地图之前对其进行截图并添加为背景。但还有一个问题,在 iPhoneX 上截屏大约需要 0.3 秒(我想在旧手机上更糟)。有没有办法在后台线程上截取 UIView 的屏幕截图?

标签: iosswiftuiviewios-multithreading

解决方案


我使用 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.


推荐阅读