简体   繁体   中英

Understanding AlphaBlending in Windows

I have a 32bpp bitmap image which has an alpha channel with values ranging from 0-255. I am trying to display this in a window using win32 APIs (snippet of code I am using to display is appended).

I was reading the documentation and it turns out that for blending, in the case where I want to use per-pixel values, windows uses the following formula:

Dst.Red     = Src.Red   + (1 - Src.Alpha) * Dst.Red
Dst.Green   = Src.Green + (1 - Src.Alpha) * Dst.Green
Dst.Blue    = Src.Blue  + (1 - Src.Alpha) * Dst.Blue

This is weird. I would have expected it to use:

Dst.Red     =  Src.Alpha*Src.Red    + (1 - Src.Alpha) * Dst.Red
Dst.Green   =  Src.Alpha*Src.Green  + (1 - Src.Alpha) * Dst.Green
Dst.Blue    =  Src.Alpha*Src.Blue   + (1 - Src.Alpha) * Dst.Blue

because that is what creates the overlay effect (translucency).

Is my expectation correct? If yes, why is windows doing the blending in this manner? What am I missing here?

snippet of code I am using to paint the Layered Window:

            bf.BlendOp = AC_SRC_OVER;
            bf.BlendFlags = 0;
            bf.SourceConstantAlpha = 255;  
            bf.AlphaFormat = AC_SRC_ALPHA;              
            POINT ptOrigin = { 0, 0 };
            SIZE windowSize = { 300, 300 };

            POINT ptZero = { 0, 0 };

            UpdateLayeredWindow(m_sThis->m_hWnd, dc, &ptOrigin, &windowSize,
                hdc, &ptZero, RGB(255, 255, 255), &bf, ULW_ALPHA);

From the documentation :

Note that the APIs use premultiplied alpha, which means that the red, green and blue channel values in the bitmap must be premultiplied with the alpha channel value. For example, if the alpha channel value is x, the red, green and blue channels must be multiplied by x and divided by 0xff prior to the call.

So, you are right, but you have to do it by hand before.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM