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 />

}<br />

nMode=dc.SetROP2(R2_XORPEN);<br />

if(m_bNeedErase == TRUE)<br />

{<br />

dc.Rectangle(m_rectDraw);<br />

}<br />

else m_bNeedErase=TRUE;<br />

m_rectDraw.right=point.x;<br />

m_rectDraw.bottom=point.y;<br />

dc.Rectangle(m_rectDraw);<br />

dc.SetROP2(nMode);<br />

dc.SelectObject(ptrBrushOld);<br />

brush.Detach();<br />

dc.SelectObject(ptrPenOld);<br />

}<br />

CView::OnMouseMove(nFlags, point);<br />

Also, function CGDIView::OnDraw(…) is modified as follows:<br />

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

{<br />

CPen pen;<br />

CPen *ptrPenOld;<br />

CBrush brush;<br />

CBrush *ptrBrushOld;<br />

int nMode;<br />

int nNumOfRects;<br />

int i;<br />

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

ASSERT_VALID(pDoc);<br />

}<br />

pen.CreatePen(PS_SOLID, 1, RGB(0, 255, 0));<br />

ptrPenOld=pDC->SelectObject(&pen);<br />

brush.CreateSolidBrush(RGB(255, 0, 255));<br />

ptrBrushOld=pDC->SelectObject(&brush);<br />

nMode=pDC->SetROP2(R2_COPYPEN);<br />

nNumOfRects=pDoc->GetNumOfRects();<br />

for(i=0; iRectangle(pDoc->GetRect(i));<br />

}<br />

pDC->SetROP2(nMode);<br />

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

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

With the above implementation, the application will be able to let the user draw rectangles.<br />

With only minor modifications we can let the application draw ellipses. Sample 8.2-2\GDI<br />

demonstrates how to implement interactive ellipse drawing. It is based on sample 8.2-1\GDI.<br />

To draw an ellipse, we need to call function CDC::Ellipse(…)and pass a CRect type value to it. This is<br />

exactly the same with calling function CDC::Rectangle(…). So in the previous sample, if we change all the<br />

“Rectangle” keywords to “Ellipse”, the application will be implemented to draw ellipses instead of<br />

rectangles.<br />

In sample 8.2-2\GDI, function CDC::Ellipse(…) is called within CGDIView::OnMouseMove(…) and<br />

CGDIView::OnDraw(…). The following shows the modified portion of two functions:<br />

……<br />

void CGDIView::OnMouseMove(UINT nFlags, CPoint point)<br />

{<br />

if(m_bNeedErase == TRUE)<br />

{<br />

dc.Ellipse(m_rectDraw);<br />

}<br />

else m_bNeedErase=TRUE;<br />

m_rectDraw.right=point.x;<br />

m_rectDraw.bottom=point.y;<br />

210

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

Saved successfully!

Ooh no, something went wrong!