How to use MeasureString in C# to set table column width?

前端 未结 3 1995
花落未央
花落未央 2021-01-27 00:59

I have a pretty quick (and I\'m hoping basic) question. I\'m modifying some C# code for my company\'s website. The code draws a table for me in fixed columns, the data for which

相关标签:
3条回答
  • 2021-01-27 01:01

    You can either use e.Graphics.MeasureString() or TextRenderer.MeasureText()

    Differences and advantages of each of them are describe here:

    TextRenderer.MeasureText and Graphics.MeasureString mismatch in size

    There you will also find usage examples, which I would skip here to avoid duplication.

    0 讨论(0)
  • 2021-01-27 01:14

    I believe you need to use this overload for MeasureString(string,font,int):

    The width parameter specifies the maximum value of the width component of the returned SizeF structure (Width). If the width parameter is less than the actual width of the string, the returned Width component is truncated to a value representing the maximum number of characters that will fit within the specified width. To accommodate the entire string, the returned Height component is adjusted to a value that allows displaying the string with character wrap.

    -- From Above Linked MSDN Page (Emphasis mine)

    // Measure string (you'll need to instansiate your own graphics object, 
    // since you wont have PaintEventArgs)
    SizeF stringSize = new SizeF();
    stringSize = e.Graphics.MeasureString(measureString, stringFont, stringWidth);
    int cellHeight = stringSize.Height;
    
    0 讨论(0)
  • 2021-01-27 01:16

    MSDN gives an example where you calculate this by registering an event handler to the OnPaint method of your control (in instantiated controls), or by overriding the OnPaint method (in inherited controls), or by overriding the OnPaint method of your form (not best practice since you probably don't want to do this for EVERY form repaint). The OnPaint method will give you access to a graphics object so you can call the MeasureString method.

    Consider the following:

    public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
                label1.Paint += new PaintEventHandler(label1_Paint);
            }
    
            void label1_Paint(object sender, PaintEventArgs e)
            {
                SizeF size = e.Graphics.MeasureString(label1.Text, label1.Font);
                this.label1.Width = (int)size.Width;
                this.label1.Height = (int)size.Height;
            }
        }
    
    0 讨论(0)
提交回复
热议问题