Working with Rectangles
Before learning how to draw shapes, you need to understand the concept of a rectangle as it relates to C# programming. A rectangle isn't necessarily used to draw a rectangle (although it can be). Rather, a rectangle is a structure used to hold bounding coordinates used to draw a shape. Obviously, a square or rectangle can fit within a rectangle. However, so can circles and ellipses. Figure 3 illustrates how most shapes can be bound by a rectangle.
Figure 3 Rectangles are used to define the bounds of most shapes.
To draw most shapes, you must have a rectangle. The rectangle you pass to a drawing method is used as a bounding rectangle; the proper shape (circle, ellipse, and so on) is always drawn. Creating a rectangle is easy. First, you dimension a variable as Rectangle and then you set the X, Y, Width, and Height properties of the object variable. The X, Y value is the coordinate of the upper-left corner of the rectangle. For example, the following code creates a rectangle that has its upper-left corner at coordinate 0,0, has a width of 100, and a height of 50:
Rectangle rectBounding = new Rectangle(); rectBounding.X = 0; rectBounding.Y = 0; rectBounding.Width = 100; rectBounding.Height = 50;
The Rectangle object enables you to send the X, Y, Height, and Width values as part of its initialize construct. Using this technique, you could create the same rectangle with only a single line of code:
Rectangle rectBounding = new Rectangle(0,0,100,50);
You can do a number of things with a rectangle after it's defined. Perhaps the most useful is the capability to enlarge or shrink the rectangle with a single statement. You enlarge or shrink a rectangle using the Inflate() method. The most common syntax of Inflate() is the following:
object.Inflate(changeinwidth, changeinheight);
When called this way, the rectangle width is enlarged (the left side of the rectangle remains in place) and the height is enlarged (the top of the rectangle stays in place). To leave the size of the height or width unchanged, pass 0 as the appropriate argument. To shrink a dimension, specify a negative number.
If you're going to do much with drawing, you'll use a lot of Rectangle objects, and I strongly suggest that you learn as much about them as you can.