Search code examples
c++transparencygdi

GDI functions set alpha channel to 0 when drawing. Why?


I've created 32-bit DIB section, do fill it with some non-zero values (FillMemory) and do a drawing on it using GDI function. I've looked at the memory of the DIB section and saw that every 4th byte (alpha channel) has a 0 now. I had the explanation for this behavior some years ago but didn't manage to find it again (and can't rememer why GDI acts like that). Anybody know why it GDI functions sets alpha channel to 0? Is there any specification for this behavior?

The idea is this:

    dib = CreateDIBSection(hdc..., &bytes);
    FillMemory(bytes,...255);
    memdc = CreateCompatibleDC(hdc);
    SelectObject(memdc, bid);
    MoveTo(memdc,...);
    LineTo(memdc,...);
    // look at every pixel in bytes
    // if alpha == 255 then it is undrawn pixel
    // and set alpha + premultiply colors otherwise
    AlphaBlend(hdc, ... memdc,...);

This code works. But it assumes that GDI functions sets alpha to 0. I want to be sure that it is a "legal behavior".


Solution

  • It is because alpha blending has become part of drawing functionality long after Windows GDI was originally designed. You have to use relatively new functions like AlphaBlend() (is there since Windows 2000 AFAIK) to get the feature.

    Originally GDI was designed so that 32 bit color value COLORREF composed by RGB macro contains colors like that 0x00bbggrr. So like you see ... what you think are alpha channel bits are not. Those are actually set to zero by GDI. Transparency was achieved by using masks, not alpha-blending.

    The binary form of GDI COLORREF is documented by link I gave like that so behavior of your code is legal (until unlikely event that MS changes the documentation).