Graphics Programming Using C#
Painting Shapes
With the help of Graphics class of System.Drawing namespace, you can render various kinds of shapes. These include Rectangle, Filled Rectangle, Lines, Ellipse, Filled Ellipse, Pie, Filled Pie, and Polygons. This class defines methods for painting these shapes. Each method differs according to the need of the shapes. You have to learn the syntax of these methods and apply them in your programs. Don't try to memorize all of them, rather you will slowly gain experience by practice.
As already discussed in the earlier, every method on the Graphics class has to be accessed by creating an object of the Graphics class. Table 1 shows some of the methods of this class. You can add the code given on the table in Listing 1.
Purpose |
Syntax |
Example |
Rectangle |
DrawRectangle (System.Drawing.Pen, float x, float y, float width, float height) |
g.DrawRectangle (new Pen(Color.Pink,3), 15,15,200,150); |
Filled Rectangle |
FillRectangle(System.Drawing.Brush, float x, float y, float width, float height) |
g.FillRectangle (new SolidBrush(Color.Pink), 20,20,160,50); |
Line |
DrawLine(System.Drawing.Pen, float x, float y, float width, float height) |
g.DrawLine(new Pen(Color.Pink,3), 15,15,200,150); |
Ellipse |
DrawEllipse(System.Drawing.Pen, float x, float y, float width, float height) |
g.DrawEllipse(new Pen(Color.Pink,3), 15,15,200,150); |
Filled Ellipse |
FillEllipse(System.Drawing.Brush, float x, float y, float width, float height) |
g.FillEllipse (new SolidBrush(Color.Pink), 20,20,160,50); |
Pie |
DrawPie(System.Drawing.Pen, float x, float y, float width, float height) |
g.DrawPie(new Pen(Color.Black),160,30,150,170,100,110) |
FilledPie |
FillPie(System.Drawing.Brush, float x, float y, float width, float height) |
g.FillPie(new Brush(Color.Black),160,30,150,170,100,110) |
Polygon |
DrawPolygon(System.Drawing.Pen, new Point[] { new Point(x,y), new Point(x,y), new Point(x,y), new Point(x,y), new Point(x,y), new Point(x,y)}); |
g.DrawPolygon(new Pen(Color.Red,2), |
FilledPolygon |
FillPolygon(System.Drawing.Brush, |
g.FillPolygon(new Brush(Color.Red), |
Table 1: Graphics Class Methods
Using the Pen class you can specify color of the border and also the thickness. From the example given above, it can be seen that Pen class is to be applied for drawing shapes while Brush class is applied for filling shapes.
Tweaking the Unit of measurement
As you may know the default Graphics unit is Pixel. By applying the PageUnit property, you can change the unit of measurement to Inch, Millimeter etc as shown below:
Graphics g = e.Graphics; g.PageUnit = GraphicsUnit.Inch;
Page 2 of 3
This article was originally published on July 30, 2002