nhatminh12369 / BarChart

An extremely light-weight, animatable bar chart, written in Swift 5.0, XCode 10.2
MIT License
296 stars 37 forks source link

How do you add gradient to bars? #15

Open alamodey opened 3 years ago

alamodey commented 3 years ago

I'm using only two colors for the bars, and the screen looks a bit bland. I want to add a bit of polish by adding a gradient to the bars. How do I do that with BarChart?

johnbrittop commented 2 years ago

Hi @alamodey Update below function in CALayerExtension file for gradiant bar

func addCurvedLayer(curvedSegment: CurvedSegment, color: CGColor, animated: Bool, oldSegment: CurvedSegment?, color1: CGColor) { let layer = CAShapeLayer() let path = UIBezierPath(curvedSegment: curvedSegment) layer.path = path.cgPath

    let gradient = CAGradientLayer()
    gradient.frame = self.frame
    gradient.type = .axial
    gradient.colors = [color1,color]

    gradient.locations = [0, 0.5, 0.5, 1.0]
    gradient.mask = layer

    self.addSublayer(gradient)

    if animated, let segment = oldSegment {
        layer.animate(
            fromValue: UIBezierPath(curvedSegment: segment).cgPath,
            toValue: layer.path!,
            keyPath: "path")
    }
}