Title: Fill and draw pie slices in C#
Of the many methods for filling and drawing shapes provided by the Graphics class, DrawPie and FillPie are two of the most confusing. These methods draw and fill elliptical pie slices. They take as parameters:
- A brush or pen indicating how the slice should be filled or drawn.
- A rectangle or coordinates, width, and height to define a rectangle. The rectangle defines the ellipse holding the pie slice.
- Two angles that define radial lines from the center of the ellipse that determine the straight sides of the pie slice.
The angles are the most confusing parameters. The first gives the slice's starting angle in degrees clockwise from the X-axis. The second angle gives the sweep angle for the slice measured clockwise from the starting angle. Note that the both angles can be either positive or negative.
This example uses the following code to draw some sample pie slices.
// Draw pie slices.
private void Form1_Paint(object sender, PaintEventArgs e)
{
e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
const int margin = 10;
const int width = 100;
Graphics gr = e.Graphics;
Pen outline_pen = Pens.Red;
Brush fill_brush = Brushes.LightGreen;
using (Pen ellipse_pen = new Pen(Color.Blue))
{
ellipse_pen.DashPattern = new float[] { 5, 5 };
// Northeast wedge.
Rectangle rect =
new Rectangle(margin + 30, 10, width, width);
gr.DrawEllipse(ellipse_pen, rect);
gr.FillPie(fill_brush, rect, 300, 30);
gr.DrawPie(outline_pen, rect, 300, 30);
// Everything else.
rect.X += width + margin;
gr.DrawEllipse(ellipse_pen, rect);
gr.FillPie(fill_brush, rect, 300, -330);
gr.DrawPie(outline_pen, rect, 300, -330);
// East wedge.
rect.Y += width + margin;
rect.X = margin + 30;
gr.DrawEllipse(ellipse_pen, rect);
gr.FillPie(fill_brush, rect, 315, 90);
gr.DrawPie(outline_pen, rect, 315, 90);
// Everything else.
rect.X += width + margin;
gr.DrawEllipse(ellipse_pen, rect);
gr.FillPie(fill_brush, rect, 315, -270);
gr.DrawPie(outline_pen, rect, 315, -270);
// Northwest quadrant.
rect.Y += width + margin;
rect.X = margin + 30;
gr.DrawEllipse(ellipse_pen, rect);
gr.FillPie(fill_brush, rect, 180, 90);
gr.DrawPie(outline_pen, rect, 180, 90);
// Everything else.
rect.X += width + margin;
gr.DrawEllipse(ellipse_pen, rect);
gr.FillPie(fill_brush, rect, 180, -270);
gr.DrawPie(outline_pen, rect, 180, -270);
}
}
This code draws three sets of two pie slices each where each set includes a slice less than 90 degrees and a complementary slice that includes all of the ellipse not drawn in the first slice. Notice that the two slices in a set use the same starting angle and that the complementary slice's sweep angle is the first slice's angle minus 360 degrees. That's what makes it complementary to the first slice.
Download the example to experiment with it and to see additional details.
|