2016-08-12 154 views
0

我创建了一个Windows窗体应用程序与很多tableLayoutPanels,标签和按钮。在启动时以及表单大小调整时,我希望组件中的文本大小能够尽可能地适合组件,而不会削减单词的结尾。C#调整大小的字体,以适应容器

如果任何人都可以帮助一个代码片段或这样做,它会真的帮助我!

在此先感谢。

+0

使用'锚'属性,其次,张贴您的代码片段 –

+0

对不起,误解,但我没有代码片段,我想要一些代码来调整字体大小尽可能地调整已经调整大小的控件而不削减目标。 –

回答

2

作为@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; 
       } 
      } 
     } 
    } 

在你的情况与窗体上许多对象,我就随便挑一个,并用它来设置类似于上述自身的字体大小,然后为表单上的所有对象重复使用此字体大小。只要你允许合适的“误差余量”(处理单词包装等),上述技术应该可以帮助你。

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

相关问题