C++ GetTextExtent 函数完整测试代码示例
由于 GetTextExtent 函数需要使用 GDI 库,因此需要添加以下头文件和库文件:
#include <Windows.h>
#include <tchar.h>
#pragma comment(lib, "gdi32.lib")
完整代码如下:
#include <Windows.h>
#include <tchar.h>
#pragma comment(lib, "gdi32.lib")
int main()
{
HDC hdc = GetDC(NULL);
// 字符串
TCHAR str[] = _T("Hello, world!");
// 获取字体
HFONT hFont = CreateFont(
16, // 字体高度
0, // 字体宽度
0, // 字体倾斜角度
0, // 字体方向角度
FW_NORMAL, // 字体粗细
FALSE, // 是否斜体
FALSE, // 是否下划线
FALSE, // 是否删除线
DEFAULT_CHARSET, // 字符集
OUT_DEFAULT_PRECIS, // 输出精度
CLIP_DEFAULT_PRECIS, // 剪辑精度
DEFAULT_QUALITY, // 字体质量
DEFAULT_PITCH | FF_SWISS, // 字体间距和字体系列
_T("Arial") // 字体名称
);
// 选择字体
HFONT hOldFont = (HFONT)SelectObject(hdc, hFont);
// 获取字符串的宽度和高度
SIZE size;
GetTextExtentPoint32(hdc, str, _tcslen(str), &size);
// 输出宽度和高度
_tprintf(_T("Width: %d, Height: %d\n"), size.cx, size.cy);
// 恢复字体
SelectObject(hdc, hOldFont);
// 释放字体
DeleteObject(hFont);
// 释放设备上下文
ReleaseDC(NULL, hdc);
return 0;
}
原文地址: https://www.cveoy.top/t/topic/gEm7 著作权归作者所有。请勿转载和采集!