Determine Label Size based upon amount of text and font size in Winforms/C#

前端 未结 11 1645
半阙折子戏
半阙折子戏 2020-11-30 01:27

I\'d like to know if there\'s a better approach to this problem. I want to resize a label (vertically) to accomodate certain amount of text. My label has a fixed width (abou

相关标签:
11条回答
  • 2020-11-30 02:23

    I posted a user control which solves this problem in the accepted answer here: Autoscale Font in a TextBox Control so that its as big as possible and still fits in text area bounds

    The control extends RichTextBox. It has a method: ScaleFontToFit that will automatically resize the font to make all the text fit.

    Neat thing is it respects the multiline property. If it's true it allows words to wrap, Otherwise it doesn't.

    0 讨论(0)
  • 2020-11-30 02:25

    Graphics.MeasureString() will probably help you.

    This is also one of the only usecases for using the Control.CreateGraphics() call!

    0 讨论(0)
  • 2020-11-30 02:27

    According to this article you should use TextRenderer if you are going to use a Windows Form control for the final output. TextRenderer and Graphics.MeasureString will give different results, so use the one that matches your final mode of output.

    0 讨论(0)
  • 2020-11-30 02:29

    How about Graphics.MeasureString, with the overload that accepts a string, the font, and the max width? This returns a SizeF, so you can round round-off the Height.

            using(Graphics g = CreateGraphics()) {
                SizeF size = g.MeasureString(text, lbl.Font, 495);
                lbl.Height = (int) Math.Ceiling(size.Height);
                lbl.Text = text;
            }
    
    0 讨论(0)
  • 2020-11-30 02:31

    This "answer" is for future reference and to combat the initial assumption that AutoSize = true implies that it (a WinForms label) will never grow in height.

    The following link shows the various effects of AutoSize = true with other properties such as MaximumSize. Depending upon the expected use of the question it may be appropriate to follow one of these approaches.

    http://blogs.msdn.com/jfoscoding/articles/478299.aspx

    0 讨论(0)
提交回复
热议问题