This documentation is archived and is not being maintained.

Using a Pen to Draw Lines and Rectangles

To draw lines and rectangles, you need a Graphics object and a Pen object. The Graphics object provides the DrawLine method, and the Pen object stores features of the line, such as color and width.

The following example draws a line from (20, 10) to (300, 100). Assume graphics is an existing Graphics object.

Dim pen As New Pen(Color.FromArgb(255, 0, 0, 0))
e.Graphics.DrawLine(pen, 20, 10, 300, 100)
[C#]
Pen pen = new Pen(Color.FromArgb(255, 0, 0, 0));
e.Graphics.DrawLine(pen, 20, 10, 300, 100);

The first statement uses the Pen class constructor to create a black pen. The one argument passed to the Pen constructor is a Color object created with the Color.FromArgb method. The values used to create the Color object (255, 0, 0, 0) correspond to the alpha, red, green, and blue components of the color. These values define an opaque black pen.

The following example draws a rectangle with its upper-left corner at (10, 10). The rectangle has a width of 100 and a height of 50. The second argument passed to the Pen constructor indicates that the pen width is 5 pixels.

Dim blackPen As New Pen(Color.FromArgb(255, 0, 0, 0), 5)
e.Graphics.DrawRectangle(blackPen, 10, 10, 100, 50)
[C#]
Pen blackPen = new Pen(Color.FromArgb(255, 0, 0, 0), 5);
e.Graphics.DrawRectangle(blackPen, 10, 10, 100, 50);

When the rectangle is drawn, the pen is centered on the rectangle's boundary. Because the pen width is 5, the sides of the rectangle are drawn 5 pixels wide, such that 1 pixel is drawn on the boundary itself, 2 pixels are drawn on the inside, and 2 pixels are drawn on the outside. For more details on pen alignment, see Setting Pen Width and Alignment.

The following illustration shows the resulting rectangle. The dotted lines show where the rectangle would have been drawn if the pen width had been one pixel. The enlarged view of the upper-left corner of the rectangle shows that the thick black lines are centered on those dotted lines.

y748y4ez.pens1(en-us,VS.71).gif

Show: