thecoolwinter
thecoolwinter

Reputation: 1002

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?

Upvotes: 0

Views: 306

Answers (2)

Duncan C
Duncan C

Reputation: 131398

You might want to use a different color model like HSB, and vary one or more of those settings between colors. In your case it looks like you're using a bright purple and want to vary the saturation from 100% to 0%.

You could then create your colors using the UIColor initializer init(hue:saturation:brightness:alpha:)

In tinkering with it a little bit, colors with a hue of 300, 100% brightness, and saturation values of 100%, 80%, 60%, 40%, 20% and 0% looked decent.

Upvotes: 0

Vivek Radadiya
Vivek Radadiya

Reputation: 171

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.

Upvotes: 1

Related Questions