Changing OnDraw()
The single call to DrawText() in OnDraw() becomes a little more complex now. Thedocument member variables are used to set the view's appearance. Edit OnDraw() by
expanding CShowStringView in the ClassView and double-clicking OnDraw().
The color is set with CDC::SetTextColor() before the call to DrawText(). You should
always save the old text color and restore it when you are finished. The parameter to
SetTextColor() is a COLORREF, and you can directly specify combinations of red, green,
and blue as hex numbers in the form 0x00bbggrr, so that, for example, 0x000000FF is
bright red. Most people prefer to use the RGB macro, which takes hex numbers from 0x0
to 0xFF, specifying the amount of each color; bright red is RGB(FF,0,0), for instance. Add
the lines shown in Listing 8.14 before the call to DrawText() to set up everything.
Listing 8.14 SHOWSTRINGDOC.CPP - OnDraw() Additions Before DrawText() Call
COLORREF oldcolor;
switch (pDoc->GetColor())
{
case 0:
oldcolor = pDC->SetTextColor(RGB(0,0,0)); //black
break;
case 1:
oldcolor = pDC->SetTextColor(RGB(0xFF,0,0)); //red
break;
case 2:
oldcolor = pDC->SetTextColor(RGB(0,0xFF,0)); //green
break;
}
Add this line after the call to DrawText():
pDC->SetTextColor(oldcolor);
There are two approaches to setting the centering flags. The brute-force way is to list
the four possibilities (neither, horizontal, vertical, and both) and have a different
DrawText() statement for each. If you were to add other settings, this would quickly
become unworkable. It's better to set up an integer to hold the DrawText() flags and
OR in each flag, if appropriate. Add the lines shown in Listing 8.15 before the call to
DrawText().
Listing 8.15 SHOWSTRINGDOC.CPP - OnDraw() Additions After DrawText() Call
int DTflags = 0;
if (pDoc->GetHorizcenter())
{
DTflags |= DT_CENTER;
}
if (pDoc->GetVertcenter())
{
DTflags |= (DT_VCENTER|DT_SINGLELINE);
}
The call to DrawText() now uses the DTflags variable:
pDC->DrawText(pDoc->GetString(), &rect, DTflags);
Now the settings from the dialog box have made their way to the dialog box class, to
the document, and finally to the view, to actually affect the appearance of the text
string. Build and execute ShowString and then try it. Any surprises? Be sure to change
the text, experiment with various combinations of the centering options, and try all
three colors. l
No comments:
Post a Comment