Search code examples
swiftexc-bad-accessuigraphicsrenderer

Crash on creating an image from UIGraphicsImageRenderer


i'm getting a Thread 1: EXC_BAD_ACCESS (code=EXC_I386_GPFLT) when layer.render(in: context) is called where i'm trying to create a snapshot image from a custom window

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

Solution

  • Use can use bellow extension to get it

    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()