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 aCSize,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. GetTextMetricsgives 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 andBitBltorStretchBlt.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 withDraw,BitBlt,StretchBlt,AlphaBlend.Save(path)writes PNG/JPEG.CImageList: a set of same-size images; used by list/tree/toolbar controls and drawable withDraw.- Icons:
LoadIcon(resource) andpDC->DrawIcon(x, y, hIcon); useLoadImagefor 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
CFontyou create inOnDrawevery time is fine (the destructor frees it) but creating one per call is slow. Create it once. - A
CBitmapcan’t be selected into two DCs at once, and must be deselected before it is destroyed. StretchBltquality: setSetStretchBltMode(HALFTONE)(andSetBrushOrgEx) or the shrunken picture looks jagged.CImage::Loaduses GDI+ internally, so GDI+ startup is handled for you.CImageobjects don’t copy; pass by reference.- Transparent PNGs need
m_image.IsTransparencySupported()andAlphaBlend/Draw, notBitBlt. CreatePointFonttakes tenths of a point (120 = 12 pt).DT_CALCRECTmodifies the rectangle but does not draw. CallDrawTextagain to render.min/maxmacros come from<windows.h>; usestd::min/std::maxonce you defineNOMINMAX(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.