从 UIGraphicsImageRenderer 创建图像时崩溃

Crash on creating an image from UIGraphicsImageRenderer

我得到一个 线程 1:EXC_BAD_ACCESS(代码=EXC_I386_GPFLT) layer.render(in: context) 被调用 我正在尝试从自定义 window

创建快照图像
let renderer = UIGraphicsImageRenderer(bounds: bounds, format: .init(for: traitCollection))
        return renderer.image { action in
            let context = action.cgContext
            layer.render(in: context)
        }

使用可以使用波纹管扩展来获取它

private var rendererKey: UInt8 = 0
extension UIView {
    var renderer: UIGraphicsImageRenderer! {
         get {
             guard let rendererInstance = objc_getAssociatedObject(self, &rendererKey) as? UIGraphicsImageRenderer else {
                self.renderer = UIGraphicsImageRenderer(bounds: bounds)
                return self.renderer
             }
             return rendererInstance
        }
        set(newValue) {
            objc_setAssociatedObject(self, &rendererKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN)
        }
    }
    func snapImageView() -> UIImageView {
        let img:UIImage = renderer.image { ctx in
         DispatchQueue.main.async { 
              layer.render(in: ctx.cgContext)
          }
        }
        let imageView:UIImageView = UIImageView(image: img)
        imageView.frame = renderer.format.bounds
        imageView.clipsToBounds = true
        return imageView
    }
}
// Generate image and image view of any view instance
let anImageView = yourView.snapImageView()