A Journey 2 Eternity

Posts Tagged ‘Replaces color

//! Replaces a color with a fill color in a given area of a
//! Device Context
//!
//! \param hDC                   : Specifies the Device Context
//! \param rcReplaceArea     : Specifies the portion of the DC area to apply the replace operation
//! \param clrColorReplace    : Specifies the color to be replaced
//! \param clrColorFill : Specifies the fill color

void ReplaceColor(HDC hDC, CRect rcReplaceArea, COLORREF clrColorReplace, COLORREF clrColorFill)
{
	CDC* pDC = CDC::FromHandle(hDC);
	CPoint pt = rcReplaceArea.TopLeft();

	CDC memDCMonoChrome;
	memDCMonoChrome.CreateCompatibleDC(pDC);

	CBitmap bmpMonoChrome;
	bmpMonoChrome.CreateCompatibleBitmap(&memDCMonoChrome, rcReplaceArea.Width(), rcReplaceArea.Height());

	CBitmap* pOldMonoBitmap = memDCMonoChrome.SelectObject(&bmpMonoChrome);

	COLORREF nOldBkColor = pDC->SetBkColor(clrColorReplace);

	// BLT to mono dc so that mask color will have 1 set and the other colors 0
	memDCMonoChrome.BitBlt(0, 0, rcReplaceArea.Width(), rcReplaceArea.Height(), pDC, pt.x, pt.y, SRCCOPY);

	CDC memDC;
	memDC.CreateCompatibleDC(pDC);

	CBitmap bmp;
	bmp.CreateCompatibleBitmap(pDC, rcReplaceArea.Width(),

	rcReplaceArea.Height());

	CBitmap* pOldBitmap = memDC.SelectObject(&bmp);
	COLORREF nOldMemDCBkColor = memDC.SetBkColor(clrColorFill);
	COLORREF nOldMemDCTextColor =

	memDC.SetTextColor(RGB(255, 255, 255));

	// BLT to mem DC so that the monochrome white is set to fill color and the monochrome black is set to white
	memDC.BitBlt(0, 0, rcReplaceArea.Width(), rcReplaceArea.Height(), &memDCMonoChrome, 0, 0, SRCCOPY);

	// AND pDC with mem dc so that the replace color part is blackened out and all other colors remains same
	pDC->BitBlt(pt.x, pt.y, rcReplaceArea.Width(), rcReplaceArea.Height(), &memDC, 0, 0, SRCAND);
	memDC.SetTextColor(RGB(0, 0, 0));

	// BLT to mem DC so that the monochrome white is set to fill color and the monochrome black is set to black
	memDC.BitBlt(0, 0, rcReplaceArea.Width(), rcReplaceArea.Height(), &memDCMonoChrome, 0, 0, SRCCOPY);

	// OR pDC with mem dc so that all colors remains as they where except the blackened out (replace color) part receives the fill color
	pDC->BitBlt(pt.x, pt.y, rcReplaceArea.Width(), rcReplaceArea.Height(), &memDC, 0, 0, SRCPAINT);

	// Set the original values back
	memDC.SetTextColor(nOldMemDCTextColor);
	memDC.SetBkColor(nOldMemDCBkColor);
	pDC->SetBkColor(nOldBkColor);

	// Set the original bitmaps back
	memDCMonoChrome.SelectObject(pOldMonoBitmap);
	memDC.SelectObject(pOldBitmap);
}
Advertisements

Pages

Categories

August 2018
M T W T F S S
« Aug    
 12345
6789101112
13141516171819
20212223242526
2728293031  

Blog Stats

  • 28,711 hits
Advertisements