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

前端 未结 11 1616
半阙折子戏
半阙折子戏 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:07

    In some cases where you must use compact framework, which does not have any override methods for MeasureString(), you might consider calculating the height by yourself.

    private int YukseklikAyarla(string p, Font font, int maxWidth)
        {
            int iHeight = 0;
            using (Graphics g = CreateGraphics())
            {
                var sizes = g.MeasureString(p, font); // THE ONLY METHOD WE ARE ALLOWED TO USE
                iHeight = (int)Math.Round(sizes.Height);
                var multiplier = (int)Math.Round((double)sizes.Width) / maxWidth; // DIVIDING THE TEXT WIDTH TO SEE HOW MANY LINES IT CAN HAS
                if (multiplier > 0)
                {
                    iHeight = (int)(iHeight * (multiplier + 1)); // WE ADD 1 HERE BECAUSE THE TEXT ALREADY HAS A LINE
                }
            }
            return iHeight;
        }
    
    0 讨论(0)
  • 2020-11-30 02:12
    Size maxSize = new Size(495, int.MaxValue);
    _label.Height = TextRenderer.MeasureText(_label.Text , _label.Font, maxSize).Height;
    
    0 讨论(0)
  • 2020-11-30 02:14

    System.Drawing.Graphics has a MeasureString method that you can use for this purpose. Use the overload that takes a string, a font, and an int "width" parameter; this last parameter specifies the maximum width allowed for the string - use the set width of your label for this parameter.

    MeasureString returns a SizeF object. Use the Height property of this returned object to set the height of your label.

    Note: to get a Graphics object for this purpose, you can call this.CreateGraphics.

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

    Is there any downside to using the TextRenderer class to measure the string (like in Marc's response) instead of going through the work to create a Graphics object, etc?

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

    Well the 60 chars might be valid for your test text, but not all characters have the same width. For instance, compare
    llllllllllllllllllllllllllllllllllllllllllllllllllllllllllll
    and
    wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww

    They both have 60 characters, and yet have vastly differing widths.

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

    Although, its an old thread, thought it might help new visitors.

    In C#, you could use control.width

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