Zebra0.com

csharp drawing

Pie for Budget

Start a new project. There are no controls for this project.

Add this code to declare the arrays for the budget:

public partial class Form1 : Form
{
   String[] budgetItems = { "Rent", "Food", "Transportation" };
   int[] cost = { 500, 275, 300 };
   Color[] colors = { Color.Red, Color.Blue, Color.Green };
   ...

Remember that you can not draw in form load. Add the code below for the paint event:

private void Form1_Paint(object sender, PaintEventArgs e)
{
   // Find and display the total
   int total = cost.Sum();
   this.Text = "Total Budget: " + total.ToString("$0.00");
   // Get the graphics of the form.
   Graphics g = this.CreateGraphics();
   // Create a Black Brush.
   SolidBrush myBrush = new SolidBrush(Color.Black);
   // Create a rectangle 200x200 (square) for the circle.
   Rectangle myRect = new Rectangle(10, 10, 200, 200);
   g.FillPie(myBrush, myRect, 0, 360);
   // Set the starting point for the legend and the pie:
   int top = 220;
   float startAngle=0.0F;
   // Draw the pie for each budget item and draw the string for the legend.
   for (int i = 0; i < cost.Length; i++)
   {
      // Draw the pie for item
      float percent = 1.0F* cost[i] / total;
      float degrees = 360 * percent;
      // Change the brush color for each item.
      myBrush.Color = colors[i];
      g.FillPie(myBrush, myRect, startAngle, degrees);
      // Change the start angle for next item.
      startAngle += degrees;
      // Draw the string for item
      g.FillRectangle(myBrush, 10, top, 10, 10);
      g.DrawString(budgetItems[i]+cost[i].ToString(" $0.00"), this.Font,myBrush, 25, top);
      // Move the position for the legend down.
      top += 15;
   }
}
To Do: Experiment! Try reading the budget from a file.

End of lesson, Next lesson: ListBox Manager in C#