找到字符串中最长的单词并使用MeasureString
确保它适合一根线:
internal static void PaintString(string s, int x, int y, int maxHeight, int maxWidth, Graphics graphics, bool underline)
{
FontStyle fontStyle = FontStyle.Bold;
if (underline)
{
fontStyle |= FontStyle.Underline;
}
var longestWord = Regex.Split(s, @"\s+").OrderByDescending(w => w.Length).First();
using (var arial = new FontFamily("Arial"))
using (var format = new StringFormat(StringFormatFlags.LineLimit)) // count only lines that fit fully
{
int fontSize = 18;
while (fontSize > 0)
{
var boundingBox = new RectangleF(x, y, maxWidth, maxHeight);
using (var font = new Font(arial, fontSize, fontStyle))
{
int charactersFittedAll, linesFilledAll, charactersFittedLongestWord, linesFilledLongestWord;
graphics.MeasureString(s, font, boundingBox.Size, format, out charactersFittedAll, out linesFilledAll);
graphics.MeasureString(longestWord, font, boundingBox.Size, format, out charactersFittedLongestWord, out linesFilledLongestWord);
// all the characters must fit in the bounding box, and the longest word must fit on a single line
if (charactersFittedAll == s.Length && linesFilledLongestWord == 1)
{
Console.WriteLine(fontSize);
graphics.DrawString(s, font, new SolidBrush(Color.Black), boundingBox, format);
return;
}
}
fontSize--;
}
throw new InvalidOperationException("Use fewer and/or shorter words");
}
}