C#调整字体大小以适应容器

C# Resize font to fit container

我正在创建一个包含大量 tableLayoutPanel、标签和按钮的 Windows 表单应用程序。在启动时和调整表单大小时,我希望组件中的文本大小尽可能适合组件,而不会切断单词的结尾。

如果有人可以提供代码片段或其他相关帮助,那对我来说真的很有帮助!

提前致谢。

正如@Rakitić 所说,您需要确保所有内容都固定在左侧、顶部、底部和右侧。

为了说明,我使用了一个大小可填满整个表单的多行文本框。然后,我将以下代码放入 SizeChanged 事件中:

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

如果你的表单上有很多对象,我会只选择一个,并用它来设置自己的字体大小,类似于上面的字体大小,然后为表单上的所有对象重复这个字体大小。只要你允许合适的"margin for error"(处理自动换行等,上述技术应该可以帮助你。

此外,我强烈建议在 Form SizeChanged 事件中为您的表单设置最小宽度和高度,否则可能会发生愚蠢的事情!