title: Windows Forms Dynamically Sizing Text to Fit a Rectangle
body: <p>Using Windows forms, I have a <a href="https://stackoverflow.com/questions/6107108/reduce-padding-around-text-in-winforms-button">rectangle</a> in which I want to paint some text inside using <code>Graphics.DrawString</code>. What I want to do though, is create the font as large as possible, whilst keeping the text within the bounds of the rectangle and only wrapping text to the next line between words.</p>
  
  <p>e.g.</p>
  
  <pre><code>Not acceptable       Acceptable
  
     +-------+         +--------+
     | dotne |         |        |
     |   t   |         | dotnet |
     | rocks |         |  rocks |
     +-------+         +--------+
  </code></pre>
  
  <p>in semi-pseudo code, this is what I'm thinking of</p>
  
  <pre><code>string text = "This is some Text";
  StringFormat sf = new StringFormat();
  sf.Alignment = StringAlignment.Center;
  sf.LineAlignment = StringAlignment.Center;
  RectangleF rect = new RectangleF(0,0,100,100);
  float maxFontSize = 10F;
  float minFontSize = 6F;
  float fontSize = maxFontSize;
  Font font = new Font(fontFamily, fontSize);
  bool found = false;
  do
  {
      font = new Font(fontFamily, fontSize);
      if TextFitsWithinBounds(text, font, rect, sf)
          found = true;
      else
          fontSize -= 0.1F;
  } while (found == false &amp;&amp; fontSize &gt; minFontSize)
  Graphics.DrawString(text, font, Brushes.Black, rect, sf);
  </code></pre>
  
  <p>What I'm looking for is a means of implementing TextFitsWithinBounds(). Is there a class anywhere in the framework that will help me achieve this?</p>
  
  <p>MeasureString comes close, but that doesn't appear to allow me to specify the bounds.</p>