Learning Hub Search Ctrl K

MFC › 6. Graphics and Printing

Fonts, Bitmaps and Icons

Text rendering and image handling.

intermediate #mfc#cfont#cbitmap#cimage#cimagelist#drawtext#icons#dpi

Explanation

Fonts (CFont)

  • CreatePointFont(tenthsOfPoint, faceName, pDC): easiest, e.g. font.CreatePointFont(120, _T("Segoe UI")) makes a 12-point font.
  • CreateFontIndirect(const LOGFONT*): full control (weight, italic, orientation), also the result of the Font dialog.
  • Select it into the DC like any GDI object and restore the old one.
  • Measure text before placing it: pDC->GetTextExtent(str) returns a CSize, DrawText(str, rc, DT_CALCRECT | DT_WORDBREAK) calculates the rectangle that wrapped text needs. Alignment flags: DT_LEFT/CENTER/RIGHT, DT_VCENTER | DT_SINGLELINE, DT_END_ELLIPSIS.
  • GetTextMetrics gives line height and the average character width.

Bitmaps and images

  • CBitmap::LoadBitmap(IDB_NAME) loads a resource; to draw it, put it in a memory DC and BitBlt or StretchBlt.
  • CImage (header <atlimage.h>) is the practical choice: it loads PNG, JPEG, GIF, BMP from files or resources (Load(path), LoadFromResource), supports alpha, and draws with Draw, BitBlt, StretchBlt, AlphaBlend. Save(path) writes PNG/JPEG.
  • CImageList: a set of same-size images; used by list/tree/toolbar controls and drawable with Draw.
  • Icons: LoadIcon (resource) and pDC->DrawIcon(x, y, hIcon); use LoadImage for sizes other than the system default.

DPI: point-size fonts scale with the display DPI, but pixel-sized bitmaps don’t: for high-DPI monitors supply larger images or scale with StretchBlt using SetStretchBltMode(HALFTONE).

Example

#include <afxwin.h>
#include <atlimage.h>

class CPreviewView : public CView {
    DECLARE_DYNCREATE(CPreviewView)
protected:
    CImage m_image;
    CFont  m_titleFont;
    CString m_caption;

    void OnInitialUpdate() override {
        CView::OnInitialUpdate();
        m_titleFont.CreatePointFont(140, _T("Segoe UI"));          // 14 pt
        m_caption = _T("A long caption that should wrap to the width of the picture and show how DrawText calculates the needed height.");
    }

    bool LoadPicture(const CString& path) {
        m_image.Destroy();                                         // release a previous image
        HRESULT hr = m_image.Load(path);                           // PNG, JPG, GIF, BMP
        return SUCCEEDED(hr);
    }

    void OnDraw(CDC* pDC) override {
        CRect client;
        GetClientRect(&client);

        // ---- title text, centered
        CFont* pOldFont = pDC->SelectObject(&m_titleFont);
        pDC->SetTextColor(RGB(30, 60, 120));
        pDC->SetBkMode(TRANSPARENT);
        CRect title(client.left, client.top + 10, client.right, client.top + 50);
        pDC->DrawText(_T("Image preview"), title, DT_CENTER | DT_VCENTER | DT_SINGLELINE);
        pDC->SelectObject(pOldFont);

        // ---- image scaled to fit while keeping the aspect ratio
        int top = 60;
        if (!m_image.IsNull()) {
            double scale = min(double(client.Width() - 20) / m_image.GetWidth(),
                               double(client.Height() - 160) / m_image.GetHeight());
            int w = int(m_image.GetWidth() * scale), h = int(m_image.GetHeight() * scale);
            pDC->SetStretchBltMode(HALFTONE);                      // good quality shrinking
            ::SetBrushOrgEx(pDC->GetSafeHdc(), 0, 0, nullptr);
            m_image.StretchBlt(pDC->GetSafeHdc(), 10, top, w, h, SRCCOPY);
            top += h + 10;
        } else {
            pDC->TextOut(10, top, _T("(no image loaded)"));
            top += 30;
        }

        // ---- wrapped caption: measure first, then draw
        CRect text(10, top, client.right - 10, top + 1000);
        pDC->DrawText(m_caption, text, DT_CALCRECT | DT_WORDBREAK);   // text.bottom is now the needed height
        pDC->DrawText(m_caption, text, DT_WORDBREAK);

        // ---- an icon from the application resources
        HICON hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
        pDC->DrawIcon(client.right - 40, 10, hIcon);
    }
};
IMPLEMENT_DYNCREATE(CPreviewView, CView)

Common pitfalls

  • Leaking GDI objects: a CFont you create in OnDraw every time is fine (the destructor frees it) but creating one per call is slow. Create it once.
  • A CBitmap can’t be selected into two DCs at once, and must be deselected before it is destroyed.
  • StretchBlt quality: set SetStretchBltMode(HALFTONE) (and SetBrushOrgEx) or the shrunken picture looks jagged.
  • CImage::Load uses GDI+ internally, so GDI+ startup is handled for you. CImage objects don’t copy; pass by reference.
  • Transparent PNGs need m_image.IsTransparencySupported() and AlphaBlend/Draw, not BitBlt.
  • CreatePointFont takes tenths of a point (120 = 12 pt).
  • DT_CALCRECT modifies the rectangle but does not draw. Call DrawText again to render.
  • min/max macros come from <windows.h>; use std::min/std::max once you define NOMINMAX (see Using Modern C++ in MFC Projects).

Win32 vs MFC

Win32: CreateFontIndirect, LoadBitmap, CreateCompatibleDC + SelectObject + BitBlt with manual cleanup. CImage and CFont give the same capabilities with constructors/destructors. For vector shapes, anti-aliased text and alpha, see GDI+ and Printing.

Exercises

1. How do you find out the height a wrapped paragraph needs before drawing it?

Call DrawText with DT_CALCRECT | DT_WORDBREAK; it updates the rectangle’s bottom without drawing.