AlphaBlending






3.24/5 (13 votes)
Dec 12, 2005

56851

1118
This articles illustrates alpha-blending two bitmaps.
Introduction
This code snippet shows how to alpha-blend two bitmaps by using the linear interpolation formula.
Background
- Linear interpolation formula:
Let 0 <= a < 1, RGBblended = a * RGBfirst + (1 - a) * RGBsecond
- Using GetBitmapBits and SetBitmapBits by Amol Kakhandki
Using the code
Here is a function which can be used in OnPaint()
or OnDraw()
. Actually, in the sample project, I didn't prepare a function, I put the code directly in the OnPaint()
method. In this function, the new blended bitmap is placed on a second bitmap. You can implement the code and create a third bitmap for the new bitmap if you need.
The second parameter, double blend
, must be in [0,1). This number is for the first bitmap, and the second number is 1-blend
for the second bitmap.
void CAlphaBlendingDlg::AlphaBlend(CDC *pDC, double blend) { BITMAP bmpX,bmpY; CBitmap bmp1,bmp2; bmp2.LoadBitmap(IDB_BITMAP2); bmp1.LoadBitmap(IDB_BITMAP1); bmp1.GetBitmap(&bmpX); UINT* bmpBuffer=(UINT*) GlobalAlloc(GPTR, bmpX.bmWidthBytes * bmpX.bmHeight); bmp1.GetBitmapBits(bmpX.bmWidthBytes * bmpX.bmHeight, bmpBuffer); bmp2.GetBitmap(&bmpY); UINT* bmpBuffer2=(UINT*) GlobalAlloc(GPTR, bmpY.bmWidthBytes * bmpY.bmHeight); bmp2.GetBitmapBits(bmpY.bmWidthBytes * bmpY.bmHeight, bmpBuffer2); int nSize = bmpY.bmWidth * bmpY.bmHeight; for (int i = 0; i < nSize; i++) { int abR = (int) (GetR(bmpBuffer[i]) * blend + (1-blend) * GetR(bmpBuffer2[i])); int abG = (int) (GetG(bmpBuffer[i]) * blend + (1-blend) * GetG(bmpBuffer2[i])); int abB = (int) (GetB(bmpBuffer[i]) * blend + (1-blend) * GetB(bmpBuffer2[i])); bmpBuffer2[i] = RGB(abB, abG, abR); } bmp2.SetBitmapBits(bmpX.bmWidthBytes * bmpX.bmHeight, bmpBuffer2); CDC memdc; memdc.CreateCompatibleDC(pDC); memdc.SelectObject(bmp2); pDC->BitBlt(10,10,bmpX.bmWidthBytes, bmpX.bmHeight, &memdc, 0, 0, SRCCOPY); GlobalFree((HGLOBAL)bmpBuffer); GlobalFree((HGLOBAL)bmpBuffer2); memdc.DeleteDC(); }