Draw Slightly Transparent Blue Rectangle in Native Win32 GDI

sazr picture sazr · Jun 10, 2012 · Viewed 11.2k times · Source

How do I draw a blue rectangle with a alpha/transparency value of 0.5 (ie, 50% transparency) in Native Win32 C++?

Using a macro like RGBA() fails, I'm not sure how I can specify the alpha value of the brush.

SetDCPenColor(hdc, RGBA(255,255,0,127));
SetDCBrushColor(hdc, RGBA(255,255,0,127));
Rectangle(hdc, 0, 0, width, height);

Answer

chris picture chris · Jun 10, 2012

I'm pretty sure you'll need GDI+ to do it like that, but it should be there with GDI:

//in rendering function
using namespace Gdiplus;
Graphics g (hdc);
SolidBrush brush (Color (127 /*A*/, 0 /*R*/, 0 /*G*/, 255 /*B*/));
g.FillRectangle (&brush, 0, 0, width, height);

On the plus side, GDI+, although not quite as fast, has greater capabilities and visual results, and is object-oriented, which also means you don't need to worry about all those SelectObject and DeleteObject calls.

Be aware that there are a couple of extra steps when initializing/ending the program in order to use GDI+, and that everything is in the Gdiplus namespace, and -lgdiplus.

If you really need GDI, the only solution I know of is AlphaBlend, which really is a more complex method than simply drawing shapes to the device context. It's always good to get started with GDI+, as it's still in use, and is much easier to use than GDI.