Working with Pens
A pen is an object that defines line-drawing characteristics. Pens are used to define color, line width, and line style (solid, dashed, and so on), and pens are used with almost all the drawing methods you'll learn about in this hour.
C# supplies a number of predefined pens, and you can also create your own. To create your own pen, use the following syntax:
Pen variable = new Pen(color, width);
After a pen is created, you can set its properties to adjust its appearance. For example, all Pen objects have a DashStyle property that determines the appearance of lines drawn with the pen. Table 2 lists the possible values for DashStyle.
Table 2Possible Values for DashStyle
Value |
Description |
Dash |
Specifies a line consisting of dashes. |
DashDot |
Specifies a line consisting of a pattern of dashes and dots. |
DashDotDot |
Specifies a line consisting of alternating dashes and double dots. |
Dot |
Specifies a line consisting of dots. |
Solid |
Specifies a solid line. |
Custom |
Specifies a custom dash style. The Pen object contains properties that can be used to define the custom line. |
The enumeration for DashStyle is part of the Drawing.Drawing2D object. Therefore, to create a new pen and use it to draw an ellipse, for example, you could use the following code:
Pen objMyPen = new Pen(System.Drawing.Color.DarkBlue, 3); objMyPen.DashStyle = System.Drawing.Drawing2D.DashStyle.Dot;
C# includes many standard pens, which are available via the System.Drawing.Pens class, as in the following:
objPen = System.Drawing.Pens.DarkBlue;
When drawing using the techniques discussed shortly, you can use custom pens or system-defined pensit's your choice.