Home > Articles > Programming > Windows Programming

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

Drawing Shapes

Now that you've learned about the Graphics object, pens, and rectangles, you'll probably find drawing shapes to be fairly simple. Shapes are drawn by calling methods of a Graphics object. Most methods require a rectangle, which is used as the bounding rectangle for the shape, as well as a pen. In this section, I'll show you what you need to do to draw different shapes.

NOTE

I've chosen to discuss only the most commonly drawn shapes. The Graphics object contains many methods for drawing additional shapes.

Drawing Lines

Drawing lines is accomplished with the DrawLine() method of the Graphics object. DrawLine() is one of the few drawing methods that doesn't require a rectangle. The syntax for DrawLine() is

object.DrawLine(pen, x1, y1, x2, y2);

Object refers to a Graphics object and pen refers to a Pen object, both of which have already been discussed. X1, Y1 is the coordinate of the starting point of the line, whereas X2, Y2 is the coordinate of the ending point; C# draws a line between the two points, using the specified pen.

Drawing Rectangles

Drawing rectangles (and squares for that matter) is accomplished using the DrawRectangle() method of a Graphics object. As you might expect, DrawRectangle() accepts a pen and a rectangle. Following is the syntax for calling DrawRectangle() in this way:

object.DrawRectangle(pen, rectangle);

If you don't have a Rectangle object (and you don't want to create one), you can call DrawRectangle() using the following format:

object.DrawRectangle(pen, X, Y, width, height);

Drawing Circles and Ellipses

Drawing circles and ellipses is accomplished by calling the DrawEllipse() method. If you're familiar with geometry, you'll note that a circle is simply an ellipse that has the same height as it does width. This is why no specific method exists for drawing circles; DrawEllipse() works perfectly. Like the DrawRectangle() method, DrawEllipse() accepts a Pen and a Rectangle. The rectangle is used as a bounding rectangle—the width of the ellipse is the width of the rectangle, whereas the height of the ellipse is the height of the rectangle. DrawEllipse() has the following syntax:

object.DrawEllipse(pen, rectangle);

In the event that you don't have a Rectangle object defined (and again you don't want to create one), you can call DrawEllipse() with this syntax:

object.DrawEllipse(pen, X, Y, Width, Height);

Clearing a Drawing Surface

To clear the surface of a Graphics object, call the Clear() method, passing it the color to paint the surface, like this:

objGraphics.Clear(Drawing.SystemColors.Control);
  • + Share This
  • 🔖 Save To Your Account