11.04.2014 Views

Advanced MFC Programming

Advanced MFC Programming

Advanced MFC Programming

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 8. DC, Pen, Brush and Palette<br />

}<br />

lpLogPal->palPalEntry[i].peBlue=i;<br />

lpLogPal->palPalEntry[i].peFlags=NULL;<br />

}<br />

VERIFY(m_palDraw.CreatePalette(lpLogPal));<br />

delete [](BYTE *)lpLogPal;<br />

In the function a LOGPALETTE type pointer is declared, we need to use it to store the buffers allocated<br />

for creating the logical palette. The buffers are allocated through using “new” method. The following is the<br />

formulae that is used to calculate the size of the total bytes needed for creating logical palette:<br />

size of structure LOGPALETTE + (number of entries-1)×(size of structure PALETTEENTRY)<br />

Next the palette entries are filled with 256 colors ranging from dark blue to bright blue. After the<br />

logical palette is created, these buffers can be released.<br />

The following is the updated function CGDIView::OnDraw(…) in sample 8.8-1\GDI:<br />

void CGDIView::OnDraw(CDC *pDC)<br />

{<br />

CBrush brush;<br />

CRect rect;<br />

CPalette *ptrPalOld;<br />

int i;<br />

CGDIDoc *pDoc=GetDocument();<br />

ASSERT_VALID(pDoc);<br />

ptrPalOld=pDC->SelectPalette(&m_palDraw, FALSE);<br />

pDC->RealizePalette();<br />

}<br />

GetClientRect(rect);<br />

rect.bottom+=255;<br />

rect.bottom/=256;<br />

for(i=0; iFillRect(rect, &brush);<br />

brush.DeleteObject();<br />

rect.OffsetRect(0, rect.Height());<br />

}<br />

pDC->SelectPalette(ptrPalOld, FALSE);<br />

Each time the client window needs to be painted, we first call function CDC::SelectPalette(…) to<br />

select the logical palette into the device context and call function CDC::RealizePalette() to let the colors<br />

in the logical palette be mapped to the system palette. When creating the brushes, instead of using RGB<br />

macro to specify an R, G, B combination, we need to use PALETTEINDEX macro to indicate a color contained<br />

in the logical palette.<br />

Sample 8.8-2\GDI is implemented almost in the same way: first a CPalette type variable m_palDraw is<br />

declared in class CGDIView, and the palette is created in its constructor. In function CGDIView::OnDraw(…),<br />

before the client window is painted, the logical palette is selected into the device context. The following is<br />

the modified function CGDIView::OnDraw(…):<br />

void CGDIView::OnDraw(CDC *pDC)<br />

{<br />

CPen pen;<br />

CPen *ptrPenOld;<br />

CRect rect;<br />

int i;<br />

CPalette *ptrPalOld;<br />

CGDIDoc *pDoc=GetDocument();<br />

ASSERT_VALID(pDoc);<br />

ptrPalOld=pDC->SelectPalette(&m_palDraw, FALSE);<br />

226

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!