Search code examples
c++winapigdi

DrawText with outline using GDI (C++)


I'm using this code to sign a frame from webcam:

Font = CreateFont(18, 0, 0, 0, FW_BOLD, FALSE, FALSE, FALSE, ANSI_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, PROOF_QUALITY, VARIABLE_PITCH, "times");

...

HDC hDC = CreateCompatibleDC(NULL);
unsigned char * img = 0;
HBITMAP hBitmap = CreateDIBSection(hDC, &BMI, DIB_RGB_COLORS, (void**)&img, NULL, 0);
memcpy(img, CameraFrame.data, CameraFrame.size());
free(CameraFrame.data);
CameraFrame.data = img;
SelectObject(hDC, hBitmap);
SelectObject(hDC, Font);
SetBkMode(hDC, TRANSPARENT);
SetTextColor(hDC, RGB(255,255,255));
string Text = "Test";
DrawTextA(hDC, Text.c_str(), Text.size(), &rect, DT_CENTER | DT_WORDBREAK);
DeleteDC(hDC);

Of course the color scale of frames will differ, and I need the text to be visible anyway.

How to DrawText with outline? For example, white text with black outline.


Solution

  • Two approaches:

    • Draw the Text in black, but scaled slightly larger by 2 pixels (good luck) and offset by (-1,-1) then normally in white in the center.

    • Draw the Text in black, but offset { (-1,-1), (1,1), (-1,1), (1,-1) } and then in white in the center.