简体   繁体   中英

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: 饼图的坏例子

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) 好的饼图

Any ideas?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM