MFC › 6. Graphics and Printing
GDI and Device Contexts
CDC, OnDraw, pens, brushes and WM_PAINT.
Explanation
GDI (Graphics Device Interface) is Windows’ classic 2D drawing API. Everything is drawn into a device context (DC): a bundle of the target (window, printer, bitmap) plus the current drawing objects and settings. MFC wraps it as CDC:
| Class | Use |
|---|---|
CPaintDC |
inside OnPaint (it calls BeginPaint/EndPaint) |
CClientDC |
anywhere else, draws in the client area |
CWindowDC |
the whole window including frame |
CMemDC-style (CDC::CreateCompatibleDC) |
an off-screen buffer |
In a CView you override OnDraw(CDC* pDC), which is used for the screen, printing and print preview alike.
Drawing objects (CPen, CBrush, CFont, CBitmap, CRgn) are selected into the DC with SelectObject, which returns the previous object; you must select the old object back before the DC or your object goes away. Stock objects (GetStockObject(NULL_BRUSH)) need no deletion. Functions: MoveTo, LineTo, Rectangle, Ellipse, RoundRect, Polygon, FillSolidRect, TextOut, DrawText, SetTextColor, SetBkMode(TRANSPARENT).
Invalidation: never repaint from other code; mark the area dirty with Invalidate() / InvalidateRect(rc) and Windows sends WM_PAINT when idle. UpdateWindow() forces it to happen now.
Mapping modes: SetMapMode(MM_TEXT) is pixels, y down. MM_LOENGLISH / MM_LOMETRIC give real-world units with y up, so printed output looks the same size on every printer. SetViewportOrg, SetWindowExt/SetViewportExt give custom scaling.
Flicker-free drawing = double buffering: draw into a compatible memory DC and copy it to the screen once with BitBlt. Also override OnEraseBkgnd to return TRUE so the background isn’t cleared first.
Example
#include <afxwin.h>
#include <cmath>
class CChartView : public CView {
DECLARE_DYNCREATE(CChartView)
protected:
int m_values[6] = { 40, 75, 55, 90, 30, 65 };
afx_msg BOOL OnEraseBkgnd(CDC*) { return TRUE; } // we paint every pixel ourselves
void OnDraw(CDC* pDC) override {
CRect rc;
GetClientRect(&rc);
// ---- draw everything into an off-screen bitmap, then copy once
CDC mem;
mem.CreateCompatibleDC(pDC);
CBitmap bmp;
bmp.CreateCompatibleBitmap(pDC, rc.Width(), rc.Height());
CBitmap* pOldBmp = mem.SelectObject(&bmp);
mem.FillSolidRect(rc, RGB(255, 255, 255)); // background
DrawChart(&mem, rc);
pDC->BitBlt(0, 0, rc.Width(), rc.Height(), &mem, 0, 0, SRCCOPY);
mem.SelectObject(pOldBmp); // restore before 'bmp' is destroyed
}
void DrawChart(CDC* pDC, const CRect& rc) {
// axis in a dark pen
CPen axisPen(PS_SOLID, 2, RGB(40, 40, 40));
CPen* pOldPen = pDC->SelectObject(&axisPen);
pDC->MoveTo(30, 10);
pDC->LineTo(30, rc.bottom - 30);
pDC->LineTo(rc.right - 10, rc.bottom - 30);
// bars with a solid brush
CBrush barBrush(RGB(70, 130, 200));
CBrush* pOldBrush = pDC->SelectObject(&barBrush);
int barW = (rc.Width() - 60) / 6;
for (int i = 0; i < 6; ++i) {
int h = m_values[i] * (rc.Height() - 60) / 100;
CRect bar(40 + i * barW, rc.bottom - 30 - h, 40 + i * barW + barW - 8, rc.bottom - 30);
pDC->Rectangle(bar);
CString label;
label.Format(_T("%d"), m_values[i]);
pDC->SetBkMode(TRANSPARENT);
pDC->DrawText(label, bar, DT_CENTER | DT_TOP | DT_SINGLELINE);
}
// a dashed polyline, using a stock hollow brush for the marker circles
CPen dash(PS_DASH, 1, RGB(200, 60, 60));
pDC->SelectObject(&dash);
pDC->SelectStockObject(NULL_BRUSH);
for (int i = 0; i < 6; ++i) {
int h = m_values[i] * (rc.Height() - 60) / 100;
int x = 40 + i * barW + (barW - 8) / 2, y = rc.bottom - 30 - h;
if (i == 0) pDC->MoveTo(x, y); else pDC->LineTo(x, y);
pDC->Ellipse(x - 4, y - 4, x + 4, y + 4);
}
pDC->SelectObject(pOldBrush); // ALWAYS restore the originals
pDC->SelectObject(pOldPen);
}
afx_msg void OnLButtonDown(UINT nFlags, CPoint pt) {
m_values[(pt.x / 40) % 6] = std::abs(pt.y) % 100;
Invalidate(FALSE); // FALSE: don't erase the background
CView::OnLButtonDown(nFlags, pt);
}
DECLARE_MESSAGE_MAP()
};
IMPLEMENT_DYNCREATE(CChartView, CView)
BEGIN_MESSAGE_MAP(CChartView, CView)
ON_WM_ERASEBKGND()
ON_WM_LBUTTONDOWN()
END_MESSAGE_MAP()
Common pitfalls
- GDI object leaks: a
CPen/CBrushobject deletes its handle in its destructor, but not while it is selected into a DC. AlwaysSelectObject(old)before it goes out of scope; a leak makes the app slowly stop drawing. - Drawing outside
OnDraw/OnPaintisn’t repainted when the window is uncovered. - Calling
Invalidate()(which erases the background) in a tight loop causes flicker; use double buffering plusOnEraseBkgndreturningTRUE, orInvalidate(FALSE). CDC::Rectanglefills with the current brush: you get a filled box unless you selectNULL_BRUSH.LineTodraws up to but not including the end pixel;Rectangle’s right/bottom edges are exclusive.MM_LOENGLISHand similar modes make y negative downward: rectangles built with positive heights end up upside-down.NormalizeRect()fixesCRect.- Calling
pDC->functions with anullptrDC (e.g.,GetDC()failing) crashes.
Win32 vs MFC
CDC is a thin wrapper over the Win32 HDC functions (::LineTo(hdc, x, y)). MFC adds object-lifetime help for the objects and the automatic BeginPaint/EndPaint in CPaintDC, but you still manage SelectObject pairs. For anti-aliasing and alpha blending look at GDI+ and Printing.
Exercises
1. Why do you call pDC->SelectObject(pOldPen) at the end of drawing?
A GDI object can’t be deleted while it’s selected into a DC, and a DC must not keep pointing to objects that are about to be destroyed. Restoring the original object releases yours and leaves the DC in a clean state.