Disable word breaking when wrapping lines in .NET DrawString

淺唱寂寞╮ 提交于 2019-12-05 19:59:35

Find the longest word in your string and use MeasureString to ensure it fits on one line:

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");
    }
}

You could resize the control size depending upon the length/size of the string. This would make sure that the string fits in one line.

What you have got there seems to be the right answer. I dont think there is a single call to the framework method that can do all that for you. Another option if you are rending button and text in winform, you should look at the ButtonRenderer and TextRenderer class. When calling DrawText or MeasureString you can also specify TextFormatFlags which will allow you to specify WorkBreak, SingleLine or using Ellipse truncation.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!