Search code examples
c#winformsgraphicspen

C# Pen.DashPattern


I want to draw a Line between 2 rows while using drag and drop. The function of this is simply visual, so that the user knows, where he is dropping the row. The line should look like the excel onces. Here my code:

        Pen _marqueePen = new Pen(Color.Gray, 2);
        float[] dashValues = {1f,1f};
        _marqueePen.DashPattern = dashValues;

But this looks like that

enter image description here

I want to look it like that:

enter image description here

I'm WinForms and the C1 Flexgrid control.


Solution

  • You can use a Custom Pen like this:

    using (Pen pen = new Pen(Color.Gray, 4f) )
    {
        pen.DashStyle = System.Drawing.Drawing2D.DashStyle.Custom;
        pen.DashPattern = new float[] { 0.25F, 0.25F };
        // now draw your stuff.. 
    }
    

    Note the doc on MSDN:

    The elements in the dashArray array set the length of each dash 
    and space in the dash pattern. The first element sets the length of a dash, 
    the second element sets the length of a space, the third element sets 
    the length of a dash, and so on. Consequently, each element should be a 
    non-zero positive number.
    
    The length of each dash and space in the dash pattern is the product 
    of the element value in the array and the width of the Pen.
    

    You can pick any pen width and any dash&gap lengths as long as you keep their relation in mind.. So if you want the finest dashes, make sure they multiply to 1.0 pixels!

    Here is the resulting line:

    fine dashed line