How to draw custom dashed/dotted lines on a canvas.

By: Vincent Drake

Abstract: Describes the use of ExtCreatePen to customize the length of your dotted lines.


Can I create custom dotted and dashed lines when drawing to the canvas? The Pen styles psDashed and psDotted don't look right for my purposes.


The VCL doesn't directly provide this function, but it is available to you through the Windows API function ExtCreatePen. The following example demonstrates the use of this function. The example creates a pen with a dash pattern that incrementally gets longer. The created pen handle is then assigned to the canvas pen, then the line is drawn.


void __fastcall TForm1::Button1Click(TObject *Sender)
        LOGBRUSH lbrush = { BS_SOLID, RGB(0,0,0), NULL};
        DWORD userstyle[] = {2, 2, 4, 4, 8, 8, 16, 16, 32, 32};

        Canvas->Pen->Handle = ExtCreatePen(PS_COSMETIC | PS_USERSTYLE, 1, &lbrush, 10, userstyle);
        Canvas->MoveTo(0, 0);
        Canvas->LineTo(400, 400);

Server Response from: ETNASC04