Unfortunately you do need to use a Graphics object to do this.
The code I use (which returns a RectangleF, because I want to know both the width and the height) is as follows:
/// <summary> The text bounding box. </summary>
private static readonly RectangleF __boundingBox = new RectangleF(29, 25, 90, 40);
/// <summary>
/// Gets the width of a given string, in the given font, with the given
/// <see cref="StringFormat"/> options.
/// </summary>
/// <param name="text">The string to measure.</param>
/// <param name="font">The <see cref="Font"/> to use.</param>
/// <param name="fmt">The <see cref="StringFormat"/> to use.</param>
/// <returns> The floating-point width, in pixels. </returns>
private static RectangleF GetStringBounds(string text, Font font,
StringFormat fmt)
{
CharacterRange[] range = { new CharacterRange(0, text.Length) };
StringFormat myFormat = fmt.Clone() as StringFormat;
myFormat.SetMeasurableCharacterRanges(range);
using (Graphics g = Graphics.FromImage(
new Bitmap((int) __boundingBox.Width, (int) __boundingBox.Height)))
{
Region[] regions = g.MeasureCharacterRanges(text, font,
__boundingBox, myFormat);
return regions[0].GetBounds(g);
}
}
This will return a RectangleF of the size of the entire text string, word-wrapped as necessary, according to the bounding box specified as __boundingBox. On the plus side, the Graphics object is destroyed as soon as the using statement is complete…