如果文本在空白处打破,你如何计算在X行中显示字符串所需的最小宽度?
答案 0 :(得分:1)
可能的提示:也许某种使用Graphics.MeasureString()的二进制搜索?
答案 1 :(得分:0)
编辑:没有意识到您想尝试将文本调整为固定数量的行。这是一个艰难的尝试和解决。这是我能想到的最好的,可能不是最优雅的,但似乎有效:
public SizeF CalculateWidth(Font font, Graphics graphics, int numOfLines,
string text)
{
SizeF sizeFull = graphics.MeasureString(text, font,
new SizeF(
float.PositiveInfinity,
float.PositiveInfinity),
StringFormat.
GenericTypographic);
float width = sizeFull.Width/numOfLines;
float averageWidth = sizeFull.Width/text.Length;
int charsFitted;
int linesFilled;
SizeF needed = graphics.MeasureString(text, font,
new SizeF(width,
float.
PositiveInfinity),
StringFormat.
GenericTypographic,
out charsFitted,
out linesFilled);
while (linesFilled > numOfLines)
{
width += averageWidth;
needed = graphics.MeasureString(text, font,
new SizeF(width,
float.PositiveInfinity),
StringFormat.GenericTypographic,
out charsFitted, out linesFilled);
}
return needed;
}
使用示例:
Font font = new Font("Arial", 12, FontStyle.Regular,
GraphicsUnit.Pixel);
Graphics g = Graphics.FromImage(new Bitmap(1, 1));
string text = "Some random text with words in it.";
SizeF size = CalculateWidth(font, g, 3, text);