AlphaBlend生成错误的颜色

时间:2014-07-06 12:16:16

标签: c++ windows winapi bitmap alphablending

我已经设法避开Windows GDI几十年了,现在我付出了代价。以下C ++代码不会产生正确的颜色。它只是应该填充一个窗口,然后alpha混合一个位图。所有alpha都是位图中的每像素alpha。

// Create a memory DC
HDC hdcMem = CreateCompatibleDC(hdc);
HBITMAP hbmMem = CreateCompatibleBitmap(hdc, cxWnd, cyWnd);
SelectObject(hdcMem, hbmMem);

// White-fill the BG
FillRect(hdcMem, &rectWnd, static_cast<HBRUSH>(GetStockObject(WHITE_BRUSH)));

// Alpha blend the bitmap into the memory DC
HDC hdcSrc = CreateCompatibleDC(hdcMem);
HBITMAP hbmOld = static_cast<HBITMAP>(SelectObject(hdcSrc, hbm));
BLENDFUNCTION bfn = { AC_SRC_OVER, 0, 255, AC_SRC_ALPHA };
AlphaBlend(hdcMem, x, y, cxBmp, cyBmp, hdcSrc, 0, 0, cxBmp, cyBmp, bfn);
SelectObject(hdcSrc, hbmOld);
DeleteDC(hdcSrc);

// Blit the memory DC to the screen
BitBlt(hdc, 0, 0, cxWnd, cyWnd, hdcMem, 0, 0, SRCCOPY);

我已经验证所有变量值都是正确的,并且hbm中的位图具有正确的像素颜色和alpha值。

结果显示许多错误的颜色,例如,低alpha的蓝色像素应为淡蓝色,而是暗红色。具有高alpha的像素更接近它们应该是什么。

任何帮助表示赞赏。 TIA。

1 个答案:

答案 0 :(得分:3)

答案,来自评论中的提示:每个像素中的每个颜色通道必须在混合前通过alpha预乘。

get DIB bits
for each pixel
  r = r * alpha / 255
  g = g * alpha / 255
  b = b * alpha / 255
set DIB bits

MS不会让这个东西很容易找到。在我能找到的唯一alpha混合样本中没有提示:

http://msdn.microsoft.com/en-us/library/windows/desktop/dd183353(v=vs.85).aspx