Title: Draw dashed lines in C#
To draw dashed lines, create a new Pen and set its DashStyle property to indicate the dash style you want. For example, the following code draws two dashed lines, one with the style Dash and one with the style DashDot.
using (Pen dashed_pen = new Pen(Color.Blue, 2))
{
...
dashed_pen.DashStyle = DashStyle.Dash;
e.Graphics.DrawString("Dash", this.Font,
Brushes.Black, 10, y - 8);
e.Graphics.DrawLine(dashed_pen, 100, y, 250, y);
y += 20;
dashed_pen.DashStyle = DashStyle.DashDot;
e.Graphics.DrawString("DashDot", this.Font,
Brushes.Black, 10, y - 8);
e.Graphics.DrawLine(dashed_pen, 100, y, 250, y);
y += 20;
...
}
Note that the size of the gaps in dashed lines depends on the line's width. If a line is 10 pixels wide, then the gap between dashes is 10 pixels long. Dots are the same length as the gaps and dashes are twice as long.
Don't forget to use the Pen object's Dispose method to free graphics resources. If you use the using statement as in this example, C# calls Dispose automatically for you.
Download the example to experiment with it and to see additional details.
|