2009-04-14 6 views
0

C++でGDI +を使用してキャンバスに文字列を描画します。 特定のフォントで文字列のアウトレイヤー(幅、高さ)を取得するAPIはありますか? ありがとうございました! Windowsプログラマーのソリューションに感謝します。 次のコードを書きました。GDI +でキャンバスに画像を描画するときの長さと高さの取得方法

Bitmap bitmap(1000,1000); 
    Graphics graphics(&bitmap); 
    RectF rec; 
    RectF useless; 
    graphics.MeasureString(m_sWords, -1, m_pFont.get(), useless, &rec); 
    int WordWidth = rec.Width + 1; 
    int WordHeight Height = rec.Height + 1; 

MeasureStringを呼び出すために実際のグラフィックを使用する必要がありますか?大きなグラフィックスインスタンスを作成せずにwordwidth、wordheightを得る方法はありますか?私はそれがリソースcomsumingであることがわかった。

答えて

2

Graphics :: MeasureStringは近似値を計算します。

1

残念ながら、これを行うにはGraphicsオブジェクトを使用する必要があります。

次のように私は(私は幅と高さの両方を知りたいので、RectangleFを返す)を使用するC#のコードは次のとおりです。

/// <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。プラス側では、usingステートメントが完了するとすぐにGraphicsオブジェクトが破棄されます。

GDI +はこれでかなり信頼性が低いようです。私はそれがかなりバギーであることがわかりました(たとえばmy question “Graphics.MeasureCharacterRanges giving wrong size calculations in C#.Net?”を参照)。 をSystem.Windows.Formsから使用できる場合は、してください。

1

絵が完成するには:

テキストが与えられた文字列であり、与えられたフォントをフォント
Dim p As New GraphicsPath 

Using stringFormat As New StringFormat() 
    stringFormat.Trimming = StringTrimming.EllipsisCharacter 
    stringFormat.LineAlignment = StringAlignment.Center 
    stringFormat.Alignment = StringAlignment.Near 

    p.AddString(text, font.FontFamily, font.Style, font.SizeInPoints, Point.Empty, stringFormat) 
End Using 

Return p.GetBounds.Size 

:それは単にそれがDeviceContextを必要としないので優れているGraphicsPath、で行うことができます。 SizeF構造体を返します。 Graphics.MeasureStringまたはGdipMeasureString-APIよりもはるかに正確な結果が得られました。

関連する問題