Graphics
残念ながら、これを行うにはオブジェクトを使用する必要があります。
私が使用する C# コード (RectangleF
幅と高さの両方を知りたいため、 a を返します) は次のとおりです。
/// <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);
}
}
RectangleF
として指定された境界ボックスに従って、必要に応じてワードラップされた、テキスト文字列全体のサイズのを返します__boundingBox
。プラス面では、Graphics
オブジェクトはステートメントが完了するとすぐに破棄されusing
ます…</p>
余談ですが、GDI+ はこの点ではかなり信頼性が低いようです。非常にバグがあることがわかりました (たとえば、私の質問「Graphics.MeasureCharacterRanges が C#.Net で間違ったサイズの計算をしていますか?」</a> を参照してください)。TextRenderer.DrawText
fromを使用できる場合は、使用System.Windows.Forms
してください。