Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Draw Slightly Transparent Blue Rectangle in Native Win32 GDI

Tags:

c++

winapi

gdi

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);
like image 828
sazr Avatar asked Jun 10 '12 02:06

sazr


1 Answers

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.

like image 118
chris Avatar answered Oct 30 '22 11:10

chris