Sunday, May 10, 2009

C# - Graphics Object - Pie Chart


This one comes with a [Form] which contains a [PictureBox] who called [chart]

We have two classes:
- [piePart] that collects name, value, and color for each pie part in our pie chart
- [pieChart] contains a generic List collection based on [piePart] class and a method which draw the chart which called [public Image doPieChart(Size pieSize)] and returns a bitmap or generated pie chart.

Codes for pieChart and piePart classes:

using System;
using System.Text;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Collections.Generic;

namespace PieChart
{
public class piePart
{
public string pieName;
public float pieVal;
public Color pieColor;

public piePart()
{
}

public piePart(string _pieName, float _pieVal, Color _pieColor)
{
pieName = _pieName;
pieVal = _pieVal;
pieColor = _pieColor;
}
}

public class pieChart
{
public List lstPiePart = new List();

public pieChart()
{
}

public Image doPieChart(Size pieSize)
{
if (lstPiePart.Count == 0) return null;

Bitmap pieBmp = new Bitmap(pieSize.Width, pieSize.Height);
Graphics grfx = Graphics.FromImage(pieBmp);
grfx.SmoothingMode = SmoothingMode.HighQuality;

float totalPieValues = 0;
foreach (piePart aPie in lstPiePart)
{
if (aPie.pieVal <= 0)
{
string errMag =
"A Pie must have a positive value";
throw new ArgumentException(errMag);
}
totalPieValues += aPie.pieVal;
}

if ( totalPieValues <= 0 )
{
string errMsg =
"At least one Pie must have a greater than Zero value";
throw new ArgumentException(errMsg);
}

Rectangle pieRect =
new Rectangle(1, 1, pieSize.Width - 2, pieSize.Height - 2);
Pen piePen = new Pen(Color.Black, 1);
float pieStartAngle = 0;

foreach (piePart aPie in lstPiePart)
{
Brush pieBrush =
new LinearGradientBrush(pieRect,
aPie.pieColor,
Color.White,
(float)45 );
float pieSweepAngle = (aPie.pieVal / totalPieValues) * 360;
grfx.FillPie(pieBrush, pieRect, pieStartAngle, pieSweepAngle);
grfx.DrawPie(piePen, pieRect, pieStartAngle, pieSweepAngle);
pieStartAngle += pieSweepAngle;
}
return pieBmp;
}

}

}


Codes for Form class:

using System;
using System.Text;
using System.Drawing;
using System.Collections;
using System.Windows.Forms;
using System.ComponentModel;
using System.Collections.Generic;

namespace PieChart
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void Draw(object sender, PaintEventArgs e)
{
Draw();
}

private void Draw()
{
pieChart myChart = new pieChart();
myChart.lstPiePart.Add(new piePart( "Spring",
(float) 118.79,
Color.Green ) );
myChart.lstPiePart.Add(new piePart( "Summer",
(float) 67.23,
Color.Red));
myChart.lstPiePart.Add(new piePart( "Autumn",
(float) 96.14,
Color.Yellow));
myChart.lstPiePart.Add(new piePart( "Winter",
(float) 121.92,
Color.Blue));

chart.Image = myChart.doPieChart( new Size(200, 200 ) );
}

}
}

Share/Bookmark

No comments: