A Journey 2 Eternity

Replace Color of a bitmap with a new color

Posted on: March 11, 2008

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;

	// Create one DC to hold temporary data.
	BOOL 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;
}
Advertisements
Tags:

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Pages

Categories

March 2008
M T W T F S S
« Dec   Apr »
 12
3456789
10111213141516
17181920212223
24252627282930
31  

Blog Stats

  • 26,968 hits
%d bloggers like this: