Home .NET Drawing a pie chart

Drawing a pie chart

by admin

Somehow I needed to add a nice 3-d pie chart to my project.
While the crowd was deciding what component to spend money on, I drew this chart:
Drawing a pie chart
Who needs it, I’m sharing the prototype code, it’s minimal :

private static void Draw3DPie( int [] sectors, PaintEventArgs e)
{
const int x = 50;
const int y = 50;
int width = 300;
int height = 120;
int sideHeight = 40;
e. Graphics SmoothingMode = SmoothingMode.AntiAlias;
int sectorId = 0;
float startAngle = 0x0;
bool hidenSide = false ;
foreach ( int sector in sectors) {
Random rnd = new Random ( ( int ) ( sector + DateTime Now.Ticks + sectorId++) );
Color color = Color.FromArgb(
rnd.Next(0, 255),
rnd.Next(0, 255),
rnd.Next(0, 255)
);
if (!hidenSide) {
GraphicsPath path = new GraphicsPath();
GraphicsPath buff = new GraphicsPath();
float angleBeizier = sector;
if ( startAngle + sector >= 180 ) {
angleBeizier = 180 - startAngle;
hidenSide = true ;
}
path.AddArc(x, y, width, height, startAngle, angleBeizier);
buff.AddArc(x, y + sideHeight, width, height, startAngle, angleBeizier);
buff.Reverse();
path.AddPath(buff, true );
// Drawing 3d sides
e. Graphics FillPath( new SolidBrush (color), path);
e. Graphics FillPath( new SolidBrush (Color.FromArgb(81, 0, 0, 0)), path);
e. Graphics DrawPath( new Pen( new SolidBrush (Color.Silver), 1), path);
}
// Drawing top side
e. Graphics FillPie( new SolidBrush (color), x, y, width, height, startAngle, sector);
e. Graphics DrawPie( new Pen( new SolidBrush (Color.Silver), 1), x, y, width, height, startAngle, sector);
startAngle += sector;
}
}
* This source code was highlighted with Source Code Highlighter

Take it, don’t be shy =)

You may also like