Search code examples
iosswiftuiviewuiimageuigraphicsimagerenderer

Weird error when trying to take a snapshot of a uiview using UIGraphicsImageRenderer


I'm getting the following error when I call this extension:

extension UIView {
    
    /// Create image snapshot of view.
    func snapshot(of rect: CGRect? = nil) -> UIImage {
        return UIGraphicsImageRenderer(bounds: rect ?? bounds).image { _ in
            drawHierarchy(in: bounds, afterScreenUpdates: true)
        }
    }
}

The error:

vImageConvert_AnyToAny - failed width = 0 height = 1 dst component = 16bit float dstLayout = ByteOrder16Little dstBytesPerRow = 0 src component = 16bit integer srcLayout = ByteOrder16Little srcBytesPerRow = 0

Any ideas why this would be the case? Wondering if a color space issue... works fine on simulator, breaks on physical device.


Solution

  • Found a solution for others that need something similar:

    extension UIView {
        
        /// Create image snapshot of view.
        func snapshot(of rect: CGRect? = nil) -> UIImage {
            
            let renderer = UIGraphicsImageRenderer(bounds: rect!)
                    return renderer.image { (context) in
                        self.layer.render(in: context.cgContext)
                    }
        }
    }