1. Fill the DC with the new color
2. Draw the bitmap transparently into the DC with the Old Color (the color to be replaced) as the mask color
Example Code :
BOOL CMFCBitmap::ReplaceColor(COLORREF crOld, COLORREF crNew)
{
CDC memDC;
CBitmap bmpTrans;
CBitmap *pOldBitmap;
POINT ptSize;
BOOL bResult;
// Create one DC to hold temporary data.
bResult = memDC.Attach(::CreateCompatibleDC(NULL));
if(bResult == FALSE)
return FALSE;
// Compute the bitmap dimension
if(!this->GetBitmapSize(&(ptSize.x), &(ptSize.y)))
return FALSE;
// Convert from device
memDC.DPtoLP(&ptSize, 1);
BITMAP bm;
GetObject(m_hBitmap, sizeof(BITMAP), (LPSTR)&bm);
CMFCBitmap bmp;
if(bmp.CopyBitmap(m_hBitmap, MFCBI_NORMAL) == FALSE)
return FALSE;
// Create the transparent bitmap
bmpTrans.Attach(this->Detach());
Attach(bmp.Detach());
// Select the bitmap
pOldBitmap = (CBitmap*)memDC.SelectObject(&bmpTrans);
CRect rc(0,0, ptSize.x, ptSize.y);
memDC.FillSolidRect(rc, crNew);
DrawTransparent(&memDC, 0,0, crOld);
memDC.SelectObject(pOldBitmap);
// Destroy the previous bitmap
DeleteObject(Detach());
HBITMAP hMaskedBitmap = (HBITMAP)bmpTrans.Detach();
// Attach to the transparent bitmap
if(!Attach(hMaskedBitmap))
{
DeleteObject((HGDIOBJ)hMaskedBitmap);
return FALSE;
}
return TRUE;
}