Pens, Lines, and Rectangles in GDI+
To draw lines with GDI+ you need to create aobject and a object. The Graphics object provides the methods that actually do the drawing, and the Pen object stores attributes, such as line color, width, and style.
Drawing a Line
To draw a line, call themethod of the Graphics object. The Pen object is passed as one of the arguments to the DrawLine method. The following example draws a line from the point (4, 2) to the point (12, 6):
DrawLine is an overloaded method of the Graphics class, so there are several ways you can supply it with arguments. For example, you can construct twoobjects and pass the Point objects as arguments to the method:
Constructing a Pen
You can specify certain attributes when you construct a Pen object. For example, one Pen constructor allows you to specify color and width. The following example draws a blue line of width 2 from (0, 0) to (60, 30):
Dashed Lines and Line Caps
The Pen object also exposes properties, such as, that you can use to specify features of the line. The following example draws a dashed line from (100, 50) to (300, 80):
You can use the properties of the Pen object to set many more attributes of the line. Theand properties specify the appearance of the ends of the line; the ends can be flat, square, rounded, triangular, or a custom shape. The property lets you specify whether connected lines are mitered (joined with sharp corners), beveled, rounded, or clipped. The following illustration shows lines with various cap and join styles.
Drawing a Rectangle
Drawing rectangles with GDI+ is similar to drawing lines. To draw a rectangle, you need a Graphics object and a Pen object. The Graphics object provides amethod, and the Pen object stores attributes, such as line width and color. The Pen object is passed as one of the arguments to the DrawRectangle method. The following example draws a rectangle with its upper-left corner at (100, 50), a width of 80, and a height of 40:
DrawRectangle is an overloaded method of the Graphics class, so there are several ways you can supply it with arguments. For example, you can construct aobject and pass the Rectangle object to the method as an argument:
Rectangle myRectangle = new Rectangle(100, 50, 80, 40); myGraphics.DrawRectangle(myPen, myRectangle);
A Rectangle object has methods and properties for manipulating and gathering information about the rectangle. For example, theand methods change the size and position of the rectangle. The method tells you whether the rectangle intersects another given rectangle, and the method tells you whether a given point is inside the rectangle.