2016-08-12 71 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中爲表單設置一個最小寬度和高度事件,否則愚蠢的事情可能發生!

相關問題