gpt4 book ai didi

c - 如何使 'DrawText' 矩形恰好适合文本?

转载 作者:行者123 更新时间:2023-12-05 01:18:30 26 4
gpt4 key购买 nike

文档 [ here ]说如果我们使用 DT_CALCRECT标志,那么下面将完成:

Determines the width and height of the rectangle. If there are multiple lines of text, DrawText uses the width of the rectangle pointed to by the pRect parameter and extends the base of the rectangle to bound the last line of text. If there is only one line of text, DrawText modifies the right side of the rectangle so that it bounds the last character in the line. In either case, DrawText returns the height of the formatted text but does not draw the text.



从描述中可以看出 DT_CALCRECT将使 DrawText 不是 绘制内容以便我应该做类似的事情
DrawTextExA(hdc, fromsqlite->descrip, -1, &rect, DT_CALCRECT, NULL);
// On debugging, I can see that rect is being modified in the above step.
if (DrawTextExA(hdc, fromsqlite->descrip, -1, &rect,
DT_LEFT | DT_EDITCONTROL | DT_WORDBREAK, NULL) == 0) {
MessageBox(NULL, L"DrawText failed", NULL, MB_OK);
}

现在的问题是矩形的宽度应该是固定的。所以,我只想要矩形的底 rect被延长。在我的情况下,虽然 fromsqlite->descrip这是从 sqlite 中检索到的数据库始终被视为 single-line文本。

任何帮助表示赞赏。

最佳答案

DT_WORDBREAK应添加以打破单行文本。
DT_CALCRECT应与最终格式结合以获得矩形。

文档:DrawText function (GDI 功能)

DT_WORDBREAK
Breaks words. Lines are automatically broken between words if a word would extend past the edge of the rectangle specified by the lpRect parameter. A carriage return-line feed sequence also breaks the line.

If this is not specified, output is on one line.



例子:
RECT rc={ 0, 0, 200, 0 };
const wchar_t* text = L"word1 word2 word3 word4 word5";
UINT format = DT_LEFT | DT_TOP | DT_EDITCONTROL | DT_WORDBREAK;
DrawText(hdc, text, -1, &rc, format | DT_CALCRECT);
DrawText(hdc, text, -1, &rc, format);

输出将类似于以下内容(取决于字体大小)

word1 word2 word3
word4 word5



DT_EDITCONTROL必要的?

考虑这个例子:
text = L"SingleLinexxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
format = DT_LEFT | DT_TOP | DT_WORDBREAK;
DrawText(hdc, text, -1, &rc, format | DT_CALCRECT);
DrawText(hdc, text, -1, &rc, format);

这次“单词”可以比矩形的宽度更长,线条不会断,文本会溢出到右侧。

您可能希望将格式与 DT_EDITCONTROL 结合使用或其他标志,如 DT_WORD_ELLIPSIS确保右侧没有溢出。
DrawTextEx使用相同的 DT_XXXX标志。

旁注:如果您的文本是 UTF-8,您可以使用 MultiByteToWideChar 转换为 UTF-16 ,而不是使用 DrawTextA需要 ANSI 输入。

关于c - 如何使 'DrawText' 矩形恰好适合文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47068265/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com