我正在使用 .NET 将字符串绘制到有限的空间中。我希望字符串尽可能大。我将字符串分成更多行(如果它留在矩形内)没有问题。现在的问题是:我不希望 .NET 在单词中间将字符串分成不同的行。例如,字符串“Test”以大字体打印在单行上。字符串“Testing”应该以较小的字体打印在单行上(而不是“Testi”在一行上,“ng”在另一行上),字符串“Test Test”应该以相当大的字体打印在两行上。
有人知道如何限制 .NET 不破坏我的话吗?
我目前正在使用这样的代码:
internal static void PaintString(string s, int x, int y, int height, int maxwidth, Graphics g, bool underline)
{
FontStyle fs = FontStyle.Bold;
if (underline)
fs |= FontStyle.Underline;
Font fnt = new System.Drawing.Font("Arial", 18, fs);
SizeF size = g.MeasureString(s, fnt, maxwidth);
while (size.Height > height)
{
fnt = new System.Drawing.Font("Arial", fnt.Size - 1, fs);
size = g.MeasureString(s, fnt, maxwidth);
}
y = (int)(y + height / 2 - size.Height / 2);
g.DrawString(s, fnt, new SolidBrush(Color.Black), new Rectangle(x, y, maxwidth, height));
}