Home   Cover Cover Cover Cover
 

Pie charts

Chap4_Ex25.cs
using System; 
using System.Collections; 
using System.Windows.Forms; 
using System.Drawing; 

public class PieChartControl : UserControl {
  private static int BORDER_SIZE = 10;
  private int[] show;
  private Color[] cls;

  public PieChartControl(int[] vs, Color[] cs) {
    show = (int[]) vs.Clone();
    cls = cs;
  }
  
  public int[] Values {
    set {
      show = (int[]) value.Clone();
      Refresh();
    }
  }
  
  public Color[] Colors {
    set {
      cls = (Color[]) value.Clone();
      Refresh();
    }
  }
  
  protected override void OnPaint(PaintEventArgs e) {
    Brush b = new SolidBrush(Color.White);  // fill color for pies
    e.Graphics.FillEllipse(b,BORDER_SIZE,BORDER_SIZE, this.Size.Width-2*BORDER_SIZE, this.Size.Height-2*BORDER_SIZE);
    int t = 0;
    for(int i=0;inew SolidBrush(cls[i]);  // fill color for pies
      e.Graphics.FillPie(b, BORDER_SIZE,BORDER_SIZE, this.Size.Width-2*BORDER_SIZE, this.Size.Height-2*BORDER_SIZE, t, show[i]);
      t+=show[i];
    }
    b = new SolidBrush(Color.Black);  
    e.Graphics.DrawEllipse(new Pen(b,3),BORDER_SIZE,BORDER_SIZE, this.Size.Width-2*BORDER_SIZE, this.Size.Height-2*BORDER_SIZE);
  }
}

public class Chap4_Ex25_Test {
  public static void Main() {
    Form f = new Form();
    PieChartControl chart = new PieChartControl(new int[] { 10, 20, 30, 40 }, new Color[] {Color.Red, Color.Green, Color.Blue, Color.Brown});
    f.Controls.Add(chart);
    f.ClientSize = chart.Size;
    Application.Run(f);
  }
}