Tuesday, January 20, 2009

Flex PieChart - fill colors

I think this may only work in Flex 3.

My goal was to get the pie charts and line charts on this one view of the dashboard all to sync up color-wise. (The line chart stuff can be found in an earlier post.)

This will also only work if you know what you'll be getting back so far as items.

Lets say I know I will be getting back the following and I know that I want each slice to have a specific coordinating color.

Hearts - Red
Spades - Blue
Clovers - Green
Stars - Yellow

I would create something called a Fill Function. This is called in the PieSeries tag. Your fill function would consist of a switch statement checking the current item, and assigning its fill. In my example code below I use a Radial Gradient, but you can use SolidColor as well.

private function myFillFunction(item:ChartItem, index:Number):IFill
var curItem:PieSeriesItem = PieSeriesItem(item);
var fill:RadialGradient = new RadialGradient();
var g1:GradientEntry = new GradientEntry();
var g2:GradientEntry = new GradientEntry();
g1.alpha = 1.0;
g2.alpha = 1.0;

switch ( curItem.item.yourProperty )
case "Hearts":
//Choose uint color values eg: 0xFFFFFF for white etc.
g1.color = LightRed;
g2.color = DarkRed;
case "Spades":
g1.color = LightBlue;
g2.color = DarkBlue;
case "Clovers":
g1.color = LightGreen;
g2.color = DarkGreen;
case "Stars":
g1.color = LightYellow;
g2.color = DarkYellow;
g1.color = LightGray;
g2.color = DarkGray;

fill.entries = [g1,g2];
return fill;



bart said...

Should make sure that the second color variable in each of the switch cases is g2

Ang said...

oh whoops! sorry! You're right. i'll fix that.

Scott said...

Really cool. I was looking for how to do this, and it solved a problem: the colors of the pie chart wouldn't stay consistent as new data arrived from the server. I did change my implementation a little. I'm using a dictionary instead of a switch statement because there are a lot of possible values.

Anonymous said...

Angela...This was very helpful, and when I was under a deadline, too. Thanks for posting.

Chowdhury said...

Hey, how to change legend item color simultaneously?