Working with Rectangles


Before learning how to draw shapes, you need to understand the concept of a rectangle as it relates to Visual C# programming. A rectangle is a structure used to hold bounding coordinates used to draw a shape. A rectangle isn't necessarily used to draw a rectangle (although it can be). Obviously, a square can fit within a rectangle. However, so can circles and ellipses. Figure 18.3 illustrates how most shapes can be bound by a rectangle.

Figure 18.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 within the confines of the bounding rectangle. 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 rectanglethe Height and Width properties are self-explanatory.

The following code creates a rectangle that has its upper-left corner at coordinate 0,0, has a width of 100, and height of 50. Note, this code simply defines a rectangle in code, it doesn't draw a rectangle to the screen:

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 ability 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 and the height are enlarged (the center 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 side, 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.




Sams Teach Yourself Microsoft Visual C# 2005 in 24 Hours, Complete Starter Kit
Sams Teach Yourself Visual C# 2005 in 24 Hours, Complete Starter Kit
ISBN: 0672327406
EAN: 2147483647
Year: N/A
Pages: 248
Authors: James Foxall

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net