1

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)
        }
Hilal
  • 23
  • 1
  • 7
  • where are you calling this block? I guess `drawRect`? – emrcftci Oct 08 '21 at 08:36
  • no i'm taking a snapshot of a viewController in unit tests i created my controller then a window then using the renderer for a screenshot i even used a pod for the screenshots and it crashed as well giving same error and on the same line layer.render(in: context) – Hilal Oct 08 '21 at 08:47
  • please check this out, maybe you'll find something -> https://stackoverflow.com/questions/19651788/whats-the-meaning-of-exception-code-exc-i386-gpflt – emrcftci Oct 08 '21 at 09:06
  • Thanks guys but unfortunately i checked them but didn't help me – Hilal Oct 08 '21 at 11:09

1 Answers1

0

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()
Jayesh Patel
  • 938
  • 5
  • 16
  • it's crashing in the same place let img:UIImage = renderer.image { ctx in layer.render(in: ctx.cgContext) } – Hilal Oct 08 '21 at 11:08
  • if you're right @Hilal should just add the following line right? `DispatchQueue.main.async { layer.render(in: context) }` – emrcftci Oct 08 '21 at 11:56