Search code examples
.netgraphicslinegdi+outline

.NET draw line with outline using GDI+


I'm using .NET for a desktop application.

I'm drawing some lines with cap start and end to use them as arrows, using Graphics.DrawLine with an apropiate pen for it, with some width (lets say 8px).

Now what i want to achive is to add an "outline" to this lines in other color, with 1 or 2 pixels width.

I don't find options to do this using GDI+ (if there is an option for this, perhaps it is in "gdiplus.dll" and i could import it with dllimport).

My first attempt was to draw first the same line with a wider pen, but the effect doesn't fit to the arrow ends as you can imagine.

Any ideas with this?

UPDATE: This is the image with my first attempt drawing two lines, one over the other:

Outlined line performed with two LineDraw operations with different pen widths


Solution

  • after much experimenting I finally got it

    use a GraphicsPath and the widen command, the one other trick is widen also widens the line to the point it sticks out past the End cap arrow, so use WidthScale on the end cap as well, then just reduce the size of the end cap

    Using bigArrow As New Drawing2D.AdjustableArrowCap(3, 3)
       bigArrow.WidthScale = 1.5
       
       Using objPen As New Pen(Color.Black, 10)
          objPen.CustomEndCap = bigArrow
    
          Using objPath As New Drawing2D.GraphicsPath
             objPath.AddLine(50, 50, 100, 100)
             Using objWidenPen As New Pen(Color.Empty, 10)
                objWidenPen.CustomEndCap = bigArrow
                objPath.Widen(objWidenPen)
             End Using
    
             gr.DrawPath(objPen, objPath)
    
          End Using
       End Using
    
       Using objPen As New Pen(Color.CornflowerBlue, 10)
          objPen.CustomEndCap = bigArrow
          gr.DrawLine(objPen, 50, 50, 100, 100)
       End Using
    End Using
    

    the result looks much better

    enter image description here