Search code examples
swiftuiviewios-charts

Bars not showing when saving Bar Chart view


My chart shows up fine in my app, but when I save the chartView to camera roll or for use in another UIViewController the bars don't show up.

Fine in my app:

enter image description here

Bars don't show up when save the chartView to camera roll or for use in another UIViewController:

enter image description here

I've tried a few ways of doing this -specifically for saving the chartView to Camera Roll- like:

1)

    let image1 = chartView.getChartImage(transparent: false)
    UIImageWriteToSavedPhotosAlbum(image1!, nil, nil, nil)

enter image description here

2)

    let image2 = captureScreen()
    UIImageWriteToSavedPhotosAlbum(image2!, nil, nil, nil)

enter image description here

3)

extension UIImage {
    convenience init(view: UIView) {
        UIGraphicsBeginImageContext(view.frame.size)
        view.layer.render(in: UIGraphicsGetCurrentContext()!)
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        self.init(cgImage: (image?.cgImage)!)
    }
}

    let image3 = UIImage(view: chartView)
    UIImageWriteToSavedPhotosAlbum(image3, nil, nil, nil)

enter image description here

But nothing works for me. Any ideas why? Thanks!


Solution

  • I had the same issue when capturing image using getChartImage. So I made my own function for capturing Image.

    Basically I make a UIView class and inherited LineChartView. Made UIView extension for taking snapShot of my chartView.

    Implement this function in UIView extension:

    func snapShot() -> UIImage? {
            UIGraphicsBeginImageContextWithOptions(self.frame.size , false, UIScreen.main.scale)
            self.layer.render(in: UIGraphicsGetCurrentContext()!)
            let image = UIGraphicsGetImageFromCurrentImageContext()
            UIGraphicsEndImageContext()
    
            return image
        }
    

    And call it like this

    let image = chartView.snapShot()
    

    Hope this helps!!!