Win32 文本绘制

· · 个人记录

文本绘制

文字的绘制

TextOut - 将文字绘制在指定坐标位置

int DrawText(
    HDC hDC,            // DC 句柄
    LPCTSTR lpString,   // 字符串
    int nCount,         // 字符数量
    LPRECT lpRect,      // 绘制文字的矩形框
    UINT uFormat        // 绘制的方式
);

文字颜色和背景

字体

字体相关

Windows 常用的字体为 TrueType 格式的字体文件
TrueType 文件保存每一个字的点阵字形

字体的使用

  1. 创建字体 CreateFont()
HFONT CreateFont(
    int nHeight,                // 字体高度
    int nWidth,                 // 字体宽度
    int nEscapement,            // 字符串旋转角度
    int nOrientation,           // 字符旋转角度
    int fnWeight,               // 字体的粗细
    DWORD fdwItalic,            // 斜体
    DWORD fdwUnderline,         // 下划线
    DWORD fdwStrikeOut,         // 删除线
    DWORD fdwCharSet,           // 字符集
    DWORD fdwOutputPrecision,   // 输出精度
    DWORD fdwClipPrecision,     // 剪切精度
    DWORD fdwQuality,           // 输出质量
    DWORD fdwPitchAndFamily,    // 匹配字体
    LPCTSTR lpszFace            // 字体名称
);
  1. 应用字体到 DC SelectObject()
  2. 绘制文字 DrawText() / TextOut()
  3. 取出字体 SelectObject()
  4. 删除字体 DeleteObject()
void OnPaint(HWND hWnd) {
    PAINTSTRUCT ps = {0};
    HDC hdc = BeginPaint(hWnd, &ps);

    SetTextColor(hdc, RGB(255, 0, 0));
    SetBkColor(hdc, RGB(0, 255, 0));
    SetBkMode(hdc, TRANSPARENT);

    HFONT hFont = CreateFont(30, 0, 45, 0, 900, 1, 1, 1, GB2312_CHARSET, 0, 0, 0, 0, "黑体");  // 宽度 0 自动
    HGDIOBJ nOldFont = SelectObject(hdc, hFont);

    char szText[] = "Hello txt long long long long long long LONG";
    TextOut(hdc, 100, 100, szText, strlen(szText));

    RECT rc;
    rc.left = 100;
    rc.top = 150; 
    rc.right = 200;
    rc.bottom = 200;
    Rectangle(hdc, 100, 150, 200, 200);
    DrawText(hdc, szText, strlen(szText), &rc, DT_CENTER | DT_VCENTER | DT_SINGLELINE | DT_NOCLIP);  // DT_VCENTER、DT_BOTTOM 只适用于 ST_SINGLELINE,和 DT_WORDBREAK 冲突

    SelectObject(hdc, nOldFont);
    DeleteObject(hFont);
    EndPaint(hWnd, &ps);
}