简体   繁体   中英

C# Resize font to fit container

I'm creating a Windows Forms Application with a lot of tableLayoutPanels, labels and buttons. At the startup and when the forms is resized, I would like the textsize in the components to fit the component best possible without cutting ends of the words.

If anyone can help with a code snippet or something for doing this, it would really help me!

Thanks in advance.

As @Rakitić says you need to make sure that everything is anchored left, top, bottom and right.

By way of illustration, I used a single multiline textbox sized to fill the entire form. I then put the following code in the SizeChanged event:

    private void textBox1_SizeChanged(object sender, EventArgs e)
    {
        TextBox tb = sender as TextBox;
        if (tb.Height < 10) return;
        if (tb == null) return;
        if (tb.Text == "") return;
        SizeF stringSize;

        // create a graphics object for this form
        using (Graphics gfx = this.CreateGraphics())
        {
            // Get the size given the string and the font
            stringSize = gfx.MeasureString(tb.Text, tb.Font);
            //test how many rows
            int rows = (int)((double)tb.Height / (stringSize.Height));
            if (rows == 0)
                return;
            double areaAvailable = rows * stringSize.Height * tb.Width;
            double areaRequired = stringSize.Width * stringSize.Height * 1.1;

            if (areaAvailable / areaRequired > 1.3)
            {
                while (areaAvailable / areaRequired > 1.3)
                {
                    tb.Font = new Font(tb.Font.FontFamily, tb.Font.Size * 1.1F);
                    stringSize = gfx.MeasureString(tb.Text, tb.Font);
                    areaRequired = stringSize.Width * stringSize.Height * 1.1;
                }
            }
            else
            {
                while (areaRequired * 1.3 > areaAvailable)
                {
                    tb.Font = new Font(tb.Font.FontFamily, tb.Font.Size / 1.1F);
                    stringSize = gfx.MeasureString(tb.Text, tb.Font);
                    areaRequired = stringSize.Width * stringSize.Height * 1.1;
                }
            }
        }
    }

In your case with many objects on the form, I would just pick one, and use it to set its own font size similar to the above, and then have this font size repeated for all objects on the form. As long as you allow suitable "margin for error" (to deal with word-wrapping etc, the above technique should help you out.

In addition I strongly recommend setting a minimum width and height for your form in the Form SizeChanged event, otherwise silly things can happen!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM