关于C#:如何计算带字体的多字符串的宽度和高度?

How to work out width and height of multined string with font?

我的程序通过计算文本的宽度和高度,并选择较小的字体(如果对于矩形而言太大),将文本字符串绘制为矩形。但是最初我只使用单行文本,现在我需要一些多行文本,我曾经使用GetTextExtentPoint32,但是如果有\\\\
在字符串中,似乎将其视为正常字符。

带有DT_CALCRECT的DrawText仅返回文本的高度...

有没有简单的方法可以做到这一点?


用于DrawText的文档指出,虽然它仅返回高度,但它修改了传递它的矩形。您是在检查矩形还是仅检查返回值?听起来您实际上想要传递一个较大宽度的矩形(即您要允许的最大宽度),并且DrawText将根据需要减小。 (如果传递的宽度较小,它将仅将其扩展为足以容纳最大的单词。)

来自MSDN:

If there are multiple lines of text, DrawText uses the width of the rectangle pointed to by the lpRect parameter and extends the base of the rectangle to bound the last line of text. If the largest word is wider than the rectangle, the width is expanded.


您应该大致执行此操作(伪代码):

1
2
3
4
5
6
7
8
9
size text_dim(0,0);
foreach( line in text.split("\
"
) )
{
  size line_dim = GetTextExtentPoint32(line.start,line.length);
  text_dim.y += line_dim.y;
  text_dim.x = max(text_dim.x,line_dim.x);
}
return text_dim;