將帶背景色的彩色位圖繪製到目標背景圖上,需去除源圖自身的背景色。
BOOL TransparentBlt(
HDC hdcDest, int xDest, int yDest, int wDest, int hDest,
HDC hdcSrc, int xSrc, int ySrc, int wSrc, int hSrc,
UINT crTransparent); // 指定透明色
CDC* pDC = GetDC();
// 載入源圖(帶紅色背景)
CBitmap bmpSrc; bmpSrc.LoadBitmap(IDB_BITMAP1);
BITMAP bmpInfo; bmpSrc.GetObject(sizeof(BITMAP), &bmpInfo);
CDC srcDC; srcDC.CreateCompatibleDC(pDC);
CBitmap* pOldSrc = srcDC.SelectObject(&bmpSrc);
// 載入目標背景圖
CBitmap bmpDest; bmpDest.LoadBitmap(IDB_BITMAP2);
BITMAP bmpDestInfo; bmpDest.GetObject(sizeof(BITMAP), &bmpDestInfo);
CDC destDC; destDC.CreateCompatibleDC(pDC);
destDC.SelectObject(&bmpDest);
// 關鍵:將源圖透明繪製到目標 DC,紅色作為透明色
TransparentBlt(destDC.m_hDC, 100, 150, bmpInfo.bmWidth, bmpInfo.bmHeight,
srcDC.m_hDC, 0, 0, bmpInfo.bmWidth, bmpInfo.bmHeight,
RGB(255, 0, 0));
// 最後將目標 DC 繪製到屏幕
BitBlt(pDC->m_hDC, 0, 0, bmpDestInfo.bmWidth, bmpDestInfo.bmHeight,
destDC.m_hDC, 0, 0, SRCCOPY);
// 釋放資源
srcDC.SelectObject(pOldSrc);
msimg32.lib(VC6 需手動添加,VS2005+ 自動鏈接)。