«« Site Rescued »»

While the site is still going to move from its current host, a new site will now take its place. More Info.

The new site may have less content, but the core will now remain. And it will now play nicely with phones! Keep an eye on the DelphiDabbler Blog for news.

» Help

How to create a pie chart

Can anyone point me in the direction of an code snippet for drawing a pie / circle given the following definition:
procedure Pie(
  ACanvas: TCanvas;
  ACenter: TPoint;
  ARadius: Integer;
  AStartDeg, AEndDeg: Float
which draws a pie as a section of a circle starting at AStartDeg dregrees (0 being straight up - or whatever) and ending at AEndDeg (360 being straight up - or whatever) using ACanvas default drawing parameters (brush and pen).

TCanvas.Pie can be used to get what you want - with a little trig. The following has 0 degrees being to the right (as in trig classes) with a positive angle in the counterclockwise direction (as in trig classes):

  Math;  {DegToRad}

procedure DrawPieSlice(const Canvas: TCanvas; const Center: TPoint;
  const Radius: Integer; const StartDegrees, StopDegrees: Double);
  Offset = 0;  {to make 0 degrees start to the right}
  X1, X2, X3, X4: Integer;
  Y1, Y2, Y3, Y4: Integer;
  X1 := Center.X - Radius;
  Y1 := Center.Y - Radius;
  X2 := Center.X + Radius;
  Y2 := Center.Y + Radius;
  {negative signs on "Y" values to correct for "flip" from normal math
  defintion for "Y" dimension}
  X3 := Center.X + Round(Radius * Cos(DegToRad(Offset + StartDegrees)));
  Y3 := Center.y - Round(Radius * Sin(DegToRad(Offset + StartDegrees)));
  X4 := Center.X + Round(Radius * Cos(DegToRad(Offset + StopDegrees)));
  Y4 := Center.y - Round(Radius * Sin(DegToRad(Offset + StopDegrees)));
  Canvas.Pie(X1, Y1, X2, Y2, X3, Y3, X4, Y4);

procedure TForm1.Button1Click(Sender: TObject);
  Center: TPoint;
  Bitmap: TBitmap;
  Radius: Integer;
  Assert (Image1.Width = Image1.Height);  {Assume square for now}
  Bitmap := TBitmap.Create;
    Bitmap.Width  := Image1.Width;
    Bitmap.Height := Image1.Height;
    Bitmap.PixelFormat := pf24bit;
    Bitmap.Canvas.Brush.Color := clRed;
    Bitmap.Canvas.Pen.Color := clBlue;
    Center := Point(Bitmap.Width div 2, Bitmap.Height div 2);
    Radius := Bitmap.Width div 2;
    DrawPieSlice (Bitmap.Canvas, Center, Radius, 0, 30);
    DrawPieSlice (Bitmap.Canvas, Center, Radius, 90, 120);
    Image1.Picture.Graphic := Bitmap;
Original resource: The Delphi Pool
Author: Earl F. Glynn
Added: 2009-11-06
Last updated: 2009-11-06

« Return to contents »