Search code examples
iosswiftuicolorios-charts

Generate Gradient of Colors for chart


I'm making a small pie chart, and I'd like to have each entry in the chart get lighter and lighter the smaller the pie slices get. I have to generate an array of UIColor to color the chart.

Here's what I have right now:

for i in 0..<entries.count {
    let percent = 1.0 - (CGFloat(i - 1)/CGFloat(entries.count))
    dataSet.colors.append(UIColor.systemPurple.withAlphaComponent(percent))
}

And it generates this: bad example of pie chart

I'd like the colors in the chart to be more like this: (sorry I just quick made it in google sheets as an example) good pie chart

Any ideas?


Solution

  • Try with this solution.

    var initialAlpha = 1.0
    
    for i in 0..<entries.count { 
        dataSet.colors.append(UIColor.systemPurple.withAlphaComponent(initialAlpha))
        initialAlpha -= 0.1
    }
    

    You can also change the difference value of 0.1 to any fraction value let's say 0.15 or 0.2 etc. according to your requirement.