在窗口中垂直居中多行文本,纯 winapi 和 C++ [英] Center multiline text vertically in a window, pure winapi and c++
问题描述
我有一个需要根据需要重绘多行文本的窗口,文本可以是可变长度的.那么如何去做呢?
I have a window that needs redrawing multiline text on demand, text could be of variable length. So how to go about doing this ?
这是我现在所拥有的,但不起作用.
This is what I have for now and it doesn't work.
RECT rc;
GetWindowRect ( hwnd, &rc );
int rectHeight = DrawText( hMemDc, text.c_str(), text.size(), &rc, DT_CALCRECT ); // Get formating rectangle height
int windowHight = rc.bottom - rc.top;
int windowWidth = rc.right - rc.left;
int yTop = rc.top + ( ( windowHight - rectHeight ) / 2 );
int yBottom = yTop + rectHeight;
int xLeft = rc.left + 20;
int xRight = rc.right - 20;
rc.top = yTop;
rc.bottom = yBottom;
rc.left = xLeft;
rc.right = xRight;
DrawText( hMemDc, text.c_str(), text.size(), &rc, DT_LEFT | DT_WORDBREAK );
推荐答案
您的代码中有两个问题.首先,您需要在 DT_CALCRECT
调用中指定 DT_WORDBREAK
否则它不会包装文本以适应可用宽度.
There are two problems in your code. First, you need to specify DT_WORDBREAK
in the DT_CALCRECT
call otherwise it won't wrap the text to fit the available width.
int rectHeight = DrawText( hMemDc, text.c_str(), text.size(), &rc,
DT_CALCRECT|DT_WORDBREAK );
其次,DT_CALCRECT
调用将使用计算出的矩形覆盖 rc
变量,因此您的窗口高度将是错误的,并且您的居中将不起作用.在 DT_CALCRECT
调用之前保存 rc
变量,或者之后再次调用 GetWindowRect
.
Second, the DT_CALCRECT
call will override the rc
variable with calculated rect, so your window height will be wrong and your centering won't work. Either save the rc
variable before the DT_CALCRECT
call, or call GetWindowRect
again afterwards.
GetWindowRect ( hwnd, &rc );
这篇关于在窗口中垂直居中多行文本,纯 winapi 和 C++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!