COLORREF = 0x00BBGGRR,每通道 8 位(0~255),理論 1677 萬色。RGB(r,g,b) 組合為 COLORREF。COLORREF 映射至實體調色板,可能產生色彩抖動。RGB 即時呈現無失真。void CMy81View::OnDraw(CDC* pDC)
{
pDC->SetBkColor(RGB(255, 0, 0)); // 背景紅
pDC->SetTextColor(RGB(198, 198, 198)); // 文字淺灰
pDC->TextOut(10, 10, _T("雷神祝大家在新的一年萬事如意!"));
}
SetBkColor/SetTextColor 若遇裝置不支援該色,會自動選擇最接近實體色。
void CMy82View::OnPrepareDC(CDC* pDC, CPrintInfo* pInfo)
{
pDC->SetMapMode(MM_ANISOTROPIC); // X/Y 比例獨立
pDC->SetWindowExt(1440, 1440); // 邏輯單位:1/1440 英吋 (twip)
pDC->SetViewportExt(pDC->GetDeviceCaps(LOGPIXELSX),
-pDC->GetDeviceCaps(LOGPIXELSY)); // 裝置像素/邏輯吋,Y 軸負號翻轉
}
此設定使 1 邏輯單位 = 1 twip,字體大小以 nPoints * 20 (twip) 指定,不受螢幕解析度影響。
class CMy82View : public CView
{
private:
void ShowFont(CDC* pDC, int& nPos, int nPoints);
// ...
};
void CMy82View::ShowFont(CDC* pDC, int& nPos, int nPoints)
{
TEXTMETRIC tm;
CFont font;
// nPoints * 20 = twip 高度,負號表示字元高度(含內部間距)
font.CreateFont(-nPoints * 20, 0, 0, 0, FW_NORMAL, FALSE, FALSE, 0,
DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS,
DEFAULT_QUALITY, DEFAULT_PITCH | FF_DONTCARE, _T("Times New Roman"));
CFont* pOldFont = pDC->SelectObject(&font);
pDC->GetTextMetrics(&tm); // 取得字體度量
CString str;
str.Format(_T("%d pt Times New Roman: Ascent=%d, Descent=%d"),
nPoints, tm.tmAscent, tm.tmDescent);
pDC->TextOut(10, nPos, str);
nPos += tm.tmHeight + tm.tmExternalLeading; // 移至下一行位置
pDC->SelectObject(pOldFont); // 還原字體,font 离开作用域自動刪除
}
void CMy82View::OnDraw(CDC* pDC)
{
int yPos = 10;
ShowFont(pDC, yPos, 8);
ShowFont(pDC, yPos, 10);
ShowFont(pDC, yPos, 12);
ShowFont(pDC, yPos, 14);
ShowFont(pDC, yPos, 18);
ShowFont(pDC, yPos, 24);
}
| 項目 | 說明 |
|---|---|
TEXTMETRIC | 字體度量:tmHeight、tmAscent、tmDescent、tmExternalLeading 等 |
CreateFont | 14 參數:高、寬、傾斜、方向、粗細、斜體、底線、刪除線、字元集、輸出精度、裁剪精度、品質、間距/家族、字體名 |
SelectObject | 將 GDI 物件(筆、刷、字體)選入 DC,傳回舊物件指標,繪製完必須還原 |
MM_ANISOTROPIC | 非等向映射模式,X/Y 比例可獨立設定,適合精確排版 |
CFont* 避免重複建立。OnPrepareDC 設定映射模式,字體大小自動適應印表機解析度。_T("微軟正黑體")、_T("新細明體") 等,並設 DEFAULT_CHARSET 或 CHINESEBIG5_CHARSET (950)。掌握色彩模型、映射模式與字體建立全流程,即可在 MFC 中實現精確、跨裝置一致的文字排版與繪圖效果。