鉴于我已经知道宽度,我需要计算字符串的高度。
例如,如果有一个字符串,如“Curabitur semper ipsum semper nulla dictum,vel vulputate elit fringilla。Donec nec placerat purus,ut blandit lectus。Maecenas non molestie nulla。Class aptent taciti sociosqu。”
我可以使用下面的代码来计算该字符串的单行宽度/高度。
using (Graphics gfx = Graphics.FromImage(new Bitmap(1, 1)))
{
System.Drawing.Font f = new System.Drawing.Font(
FontFamily.GenericSansSerif, 10, FontStyle.Regular);
SizeF bounds = gfx.MeasureString(
message, f, new PointF(0, 0),
new StringFormat(StringFormatFlags.MeasureTrailingSpaces));
}
但是,我想做的是计算该字符串的高度(如果它在 200 像素的 div 内),考虑换行。
起初我认为它是用于派生 Graphics 对象的图像宽度的函数。
using (Graphics gfx = Graphics.FromImage(new Bitmap(500, 200)))
这没有帮助,得到了相同的单线尺寸。
有谁知道获得此信息的其他技巧吗?
最佳答案
given that I already know the width
然后您当然必须将宽度告诉 MeasureString(),请注意您从未在代码中这样做。 MeasureString() 有 several overloads ,您需要使用一个采用 SizeF 的函数。例如,传递 new SizeF(500, int.MaxValue)
。您将返回的 SizeF 的宽度仍为 500,但会告诉您要查找的高度。
顺便说一句,当您绘制到打印机时,只使用 DrawString/MeasureString。对于呈现在屏幕上的文本,您应该改用 TextRenderer。
关于c# - Graphics MeasureString 方法是否/可以考虑容器的宽度和换行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20843938/