9

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);
sazr
  • 24,984
  • 66
  • 194
  • 362

2 Answers2

7

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.

chris
  • 60,560
  • 13
  • 143
  • 205
  • I don't think GDI+ Isn't faster than GDI is it? GDI is hardware accelerated but not so for GDI+ (from what I have read). – Seth Carnegie Jun 10 '12 at 03:50
  • @SethCarnegie, I haven't read too much into it, but I remembered it being faster. Looking at it, you seem to be right. GDI+ still has more capability, and produces better images, though. If you're truly worried about speed (and quality at the same time), DirectX is an extremely good candidate. – chris Jun 10 '12 at 03:52
  • Yes, there is no doubt GDI+ produces better images and has more capability. +1. – Seth Carnegie Jun 10 '12 at 03:58
  • For sure GDI+ is slower than GDI (at least where you can achieve the same results). I did some measurements and it's absolutely evident. – Nick Feb 04 '20 at 14:13