Draw dashed lines with various dash styles in C#

To create a dashed line, first create a Pen. Then set the Pen's DashStyle property.

For example, the following code draws two lines, one with DashStyle Dash and one with DashStyle 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 a dashed line 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's Dispose method to free graphics resources. If you use the using statement as in this example, C# calls Dispose automatically for you.

   

 

What did you think of this article?




Trackbacks
  • No trackbacks exist for this post.
Comments
  • No comments exist for this post.
Leave a comment

Submitted comments are subject to moderation before being displayed.

 Name

 Email (will not be published)

 Website

Your comment is 0 characters limited to 3000 characters.