user22814
user22814

Reputation: 439

WinAPI - how to draw dotted line?

I create HPEN using WinAPI GDI method:

HPEN hPen = CreatePen(PS_DOT, 1, color);

Then draw line using the methods MoveToEx and LineTo.

In fact drawn line is dashed. 3 pixels empty, 3 pixels with color -- dashed line.

Why PS_DOT style doesn't draw dotted line? How to draw dotten line using WinAPI?

Upvotes: 4

Views: 7946

Answers (4)

Kalles Fraktaler
Kalles Fraktaler

Reputation: 1

I used this instead of the above to avoid two pixels in a row

void LineDDAProc(int x, int y, LPARAM lpData)
{
   LineData* pData = (LineData*) lpData;

   if (x%2!=y%2)
    pData->pDC->SetPixel(x, y, pData->crForegroundColor);
}

Upvotes: 0

user22814
user22814

Reputation: 439

Here is wonderful solution by MaxHacher that I've found on CodeProject
(http://www.codeproject.com/KB/GDI/DOTTED_PEN.aspx)

LOGBRUSH LogBrush;
LogBrush.lbColor = color;
LogBrush.lbStyle = PS_SOLID;
HPEN hPen = ExtCreatePen( PS_COSMETIC | PS_ALTERNATE, 1, &LogBrush, 0, NULL );

It works well!

Upvotes: 5

SAMills
SAMills

Reputation: 456

I too had this problem in the past. I resorted to using LineDDA and a callback proc.

struct LineData{
    CDC* pDC;
    COLORREF crForegroundColor;
    COLORREF crBackgroundColor;
};
.
.
.
LineData* pData = new LineData;
pData->crForegroundColor = crForegroundColor;
pData->crBackgroundColor = crBackgroundColor;
pData->pDC = pdc;

LineDDA(nStartx, nStarty, nEndPointX, nEndPointY, LineDDAProc, (LPARAM) pData);
delete pData;
.
.
.

void 
LineDDAProc(int x, int y, LPARAM lpData)
{
   static short nTemp = 0;

   LineData* pData = (LineData*) lpData;

   if (nTemp == 1)
    pData->pDC->SetPixel(x, y, pData->crForegroundColor);
   else
    pData->pDC->SetPixel(x, y, pData->crBackgroundColor);
   nTemp = (nTemp + 1) % 2;
}

Might not be the most efficient drawing algorithm, but you're now in complete control of dot spacing as well. I went with this approach because there were other non-native pen styles I was using for line rendering which used a bit pattern. I then walked the bit and used setpixel for the 'on' bits. It worked well and increased the useful linestyles.

Upvotes: 1

user31394
user31394

Reputation:

I haven't tried this, but it might be worth checking the results from

HPEN hPen = CreatePen(PS_DOT, 0, color);

A pen width of zero causes GDI to always make the pen one pixel wide, regardless of the scaling associated with the device context. This may be enough to get the dots you want.

Upvotes: 0

Related Questions