Here's another solution to the problem, it's a little intensive as it requires a fair bit of font creation and destruction, but may work better, depending on your circumstances and needs:
public class RenderInBox
{
Rectangle box;
Form root;
Font font;
string text;
StringFormat format;
public RenderInBox(Rectangle box, Form root, string text, string fontFamily, int startFontSize = 150)
{
this.root = root;
this.box = box;
this.text = text;
Graphics graphics = root.CreateGraphics();
bool fits = false;
int size = startFontSize;
do
{
if (font != null)
font.Dispose();
font = new Font(fontFamily, size, FontStyle.Regular, GraphicsUnit.Pixel);
SizeF stringSize = graphics.MeasureString(text, font, box.Width, format);
fits = (stringSize.Height < box.Height);
size -= 2;
} while (!fits);
graphics.Dispose();
format = new StringFormat()
{
Alignment = StringAlignment.Center,
LineAlignment = StringAlignment.Center
};
}
public void Render(Graphics graphics, Brush brush)
{
graphics.DrawString(text, font, brush, box, format);
}
}
To use it simply create a new class and call Render(). Note this is specifically written for rendering to a form.
var titleBox = new RenderInBox(new Rectangle(10, 10, 400, 100), thisForm, "This is my text it may be quite long", "Tahoma", 200);
titleBox.Render(myGraphics, Brushes.White);
You should create the RenderInBox object upfront due to it's intensive creation nature. Therefore it's not suitable for every need.