您实际上不必自己将文本居中。如果您传递适当的标志,GDI 文本输出函数可以为您执行此操作。
例如,如果您调用DrawText
并传递DT_CENTER
标志,它将自动在指定矩形的中间(水平居中)绘制文本。
假设您只有一行文本(听起来像您这样做),您可以通过传递and标志让它自动垂直居中文本。DT_SINGLELINE
DT_VCENTER
因此,您真正需要做的就是编写代码将窗口的客户区分成 4 个相等的部分,然后将这些矩形传递给DrawText
函数。这不是很困难。如果您无法在脑海中想象它,请将铅笔和纸放在上面。
void PaintWindow(HWND hWnd)
{
// Set up the device context for drawing.
PAINTSTRUCT ps;
HDC hDC = BeginPaint(hWnd, &ps);
HPEN hpenOld = static_cast<HPEN>(SelectObject(hDC, GetStockObject(DC_PEN)));
HBRUSH hbrushOld = static_cast<HBRUSH>(SelectObject(hDC, GetStockObject(NULL_BRUSH)));
// Calculate the dimensions of the 4 equal rectangles.
RECT rcWindow;
GetClientRect(hWnd, &rcWindow);
RECT rc1, rc2, rc3, rc4;
rc1 = rc2 = rc3 = rc4 = rcWindow;
rc1.right -= (rcWindow.right - rcWindow.left) / 2;
rc1.bottom -= (rcWindow.bottom - rcWindow.top) / 2;
rc2.left = rc1.right;
rc2.bottom = rc1.bottom;
rc3.top = rc1.bottom;
rc3.right = rc1.right;
rc4.top = rc1.bottom;
rc4.left = rc1.right;
// Optionally, deflate each of the rectangles by an arbitrary amount so that
// they don't butt up right next to each other and we can distinguish them.
InflateRect(&rc1, -5, -5);
InflateRect(&rc2, -5, -5);
InflateRect(&rc3, -5, -5);
InflateRect(&rc4, -5, -5);
// Draw (differently-colored) borders around these rectangles.
SetDCPenColor(hDC, RGB(255, 0, 0)); // red
Rectangle(hDC, rc1.left, rc1.top, rc1.right, rc1.bottom);
SetDCPenColor(hDC, RGB(0, 255, 0)); // green
Rectangle(hDC, rc2.left, rc2.top, rc2.right, rc2.bottom);
SetDCPenColor(hDC, RGB(0, 0, 255)); // blue
Rectangle(hDC, rc3.left, rc3.top, rc3.right, rc3.bottom);
SetDCPenColor(hDC, RGB(255, 128, 0)); // orange
Rectangle(hDC, rc4.left, rc4.top, rc4.right, rc4.bottom);
// Draw the text into the center of each of the rectangles.
SetBkMode(hDC, TRANSPARENT);
SetBkColor(hDC, RGB(0, 0, 0)); // black
// TODO: Optionally, set a nicer font than the default.
DrawText(hDC, TEXT("Hello World!"), -1, &rc1, DT_CENTER | DT_SINGLELINE | DT_VCENTER);
DrawText(hDC, TEXT("Hello World!"), -1, &rc2, DT_CENTER | DT_SINGLELINE | DT_VCENTER);
DrawText(hDC, TEXT("Hello World!"), -1, &rc3, DT_CENTER | DT_SINGLELINE | DT_VCENTER);
DrawText(hDC, TEXT("Hello World!"), -1, &rc4, DT_CENTER | DT_SINGLELINE | DT_VCENTER);
// Clean up after ourselves.
SelectObject(hDC, hpenOld);
SelectObject(hDC, hbrushOld);
EndPaint(hWnd, &ps);
}