Looking over the internet, I didn't find any manual implementation of the
AlphaBlend
function supported by Windows. Due to some bindings of my project, I couldn't use the AlphaBlend provided by windows, so I had to implement it on my own.
I hope it (atleast the concept) becomes useful for some:
(
Note: This will only work if the source and destination dc bitmaps are equal in size.)
void AlphaBlend(CDC* pDC, int xDest, int yDest, int nDestWidth, int nDestHeight,
CDC* pSrcDC, int xSrc, int ySrc, BYTE uAlphaValue)
{
BOOL bProceed = TRUE;
CDC memDC;
if(!memDC.CreateCompatibleDC(pDC))
{
bProceed = FALSE;
}
CBitmap memBmp;
if(bProceed)
{
if(!memBmp.CreateCompatibleBitmap(pDC, nDestWidth, nDestHeight))
{
bProceed = FALSE;
}
}
if(bProceed)
{
CBitmap* pOldBmp = memDC.SelectObject(&memBmp);
memDC.BitBlt(0, 0, nDestWidth, nDestHeight, pDC, 0, 0, SRCCOPY);
CDC* pDestDC = &memDC;
ASSERT(pDestDC);
ASSERT(pSrcDC);
BYTE r1, r2, rDest;
BYTE g1, g2, gDest;
BYTE b1, b2, bDest;
BYTE av = uAlphaValue;
BYTE rem = 255 - av;
COLORREF clrPixelDest, clrPixelSrc;
for(int dy = yDest, sy = ySrc; dy < nDestHeight; dy++, sy++)
{
for(int dx = xDest, sx = xSrc; dx < nDestWidth; dx++, sx++)
{
clrPixelDest = pDestDC->GetPixel(dx, dy);
r1 = GetRValue(clrPixelDest);
g1 = GetGValue(clrPixelDest);
b1 = GetBValue(clrPixelDest);
clrPixelSrc = pSrcDC->GetPixel(sx, sy);
r2 = GetRValue(clrPixelSrc);
g2 = GetGValue(clrPixelSrc);
b2 = GetBValue(clrPixelSrc);
rDest = (r1*rem + r2*av) / 255;
gDest = (g1*rem + g2*av) / 255;
bDest = (b1*rem + b2*av) / 255;
pDestDC->SetPixel(dx, dy, RGB(rDest, gDest, bDest));
}
}
pDC->BitBlt(0, 0, nDestWidth, nDestHeight, &memDC, 0, 0, SRCCOPY);
memDC.SelectObject(pOldBmp);
}
}