11.04.2014 Views

Advanced MFC Programming

Advanced MFC Programming

Advanced MFC Programming

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

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

In the constructor, the logical palette is created as follows:<br />

CGDIView::CGDIView()<br />

{<br />

LPLOGPALETTE lpLogPal;<br />

int i;<br />

}<br />

lpLogPal=(LPLOGPALETTE) new BYTE[sizeof(LOGPALETTE)+255*sizeof(PALETTEENTRY)];<br />

lpLogPal->palVersion=0x300;<br />

lpLogPal->palNumEntries=256;<br />

for(i=0; ipalPalEntry[i].peRed)))=(WORD)i;<br />

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

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

}<br />

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

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

The procedure above is almost the same with creating a normal logical palette. The only difference<br />

here is that when stuffing structure PALETTEENTRY, the low order word of the structure is filled with an<br />

index to the system palette entry (from 0 to 255), and member peFlags is set to PC_EXPLICIT.<br />

Function CGDIView::OnDraw(…) is implemented as follows:<br />

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

{<br />

CBrush brush;<br />

CBrush *ptrBrushOld;<br />

CPalette *ptrPalOld;<br />

CRect rect;<br />

int i, j;<br />

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

ASSERT_VALID(pDoc);<br />

ASSERT(m_palSys.GetSafeHandle());<br />

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

pDC->RealizePalette();<br />

GetClientRect(rect);<br />

rect.right/=16;<br />

rect.bottom/=16;<br />

}<br />

for(j=0; jRectangle(rect);<br />

pDC->SelectObject(ptrBrushOld);<br />

brush.DeleteObject();<br />

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

}<br />

rect.OffsetRect(-16*rect.Width(), rect.Height());<br />

}<br />

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

The client area is divided into 256 (16×16) rectangles. For each rectangle, a brush using a specific<br />

logical palette entry is created. Then function CDC::Rectangle(…) is called to draw the rectangle. Because<br />

no pen is selected into the DC, the default pen will be used to draw the border of the rectangles.<br />

The application can be compiled and executed at this point. There are 256 rectangles in the client<br />

window, each represents one color contained in the system palette. By paying attention to the first 10 and<br />

last 10 entries, we will notice that the colors contained in these entries never change (because they are static<br />

228

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

Saved successfully!

Ooh no, something went wrong!