Draw lines with custom dash patterns in C#

[custom dash patterns]

To create lines with custom dash patterns, first create a Pen object and set its DashStyle property to Custom. Then set its DashPattern property to an array of floating point numbers that indicate how many units to draw and then skip. For example, the array { 5, 1 } means draw 5, skip 1, and then repeat as needed.

The drawing unit is the thickness of the line. For example, if the line is 5 pixels wide, then the array { 5, 1 } means draw 5 × 5 = 25 pixels, skip 1 × 5 = 5 pixels, and repeat.

The example program uses the following code to draw its samples.

private void Form1_Paint(object sender, PaintEventArgs e)
{
    int y = 20;
    int x1 = 65;
    int x2 = ClientSize.Width - 10;
    using (Pen dashed_pen = new Pen(Brushes.Red, 5))
    {
        dashed_pen.DashStyle = DashStyle.Custom;

        dashed_pen.DashPattern = new float[] { 3, 1 };
        e.Graphics.DrawString("3, 1", this.Font,
            Brushes.Black, 10, y - 8);
        e.Graphics.DrawLine(dashed_pen, x1, y, x2, y);
        y += 20;

        dashed_pen.DashPattern = new float[] { 5, 1, 5, 5 };
        e.Graphics.DrawString("5, 1, 5, 5", this.Font,
            Brushes.Black, 10, y - 8);
        e.Graphics.DrawLine(dashed_pen, x1, y, x2, y);
        y += 20;

        dashed_pen.DashPattern = new float[] { 5, 1 };
        e.Graphics.DrawString("5, 1", this.Font,
            Brushes.Black, 10, y - 8);
        e.Graphics.DrawLine(dashed_pen, x1, y, x2, y);
        y += 20;

        dashed_pen.DashPattern = new float[] { 1, 3 };
        e.Graphics.DrawString("1, 3", this.Font,
            Brushes.Black, 10, y - 8);
        e.Graphics.DrawLine(dashed_pen, x1, y, x2, y);
        y += 20;

        dashed_pen.DashPattern = new float[] { 3, 1, 1, 1 };
        e.Graphics.DrawString("3, 1, 1, 1", this.Font,
            Brushes.Black, 10, y - 8);
        e.Graphics.DrawLine(dashed_pen, x1, y, x2, y);
        y += 20;
    }
}

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.


Download Example   Follow me on Twitter   RSS feed   Donate




This entry was posted in drawing, graphics and tagged , , , , , , , , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *