2011-07-19 7 views
5

Graphics DrawStringメソッドを使用して画像にテキストを書き込んでいて、テキストをRectangleFでバインドしています。ここに私のコードです:これは、いくつかのケースのために働くC#Graphics.DrawString RectangleF Auto-Height:その高さを見つける方法は?

//Write header2 
RectangleF header2Rect = new RectangleF(); 
header2Rect.Width = 600; 
header2Rect.Location = new Point(30, 105); 
graphicImage.DrawString(header2, new Font("Gotham Medium", 28, FontStyle.Bold),brush, header2Rect); 
//Write Description 
RectangleF descrRect = new RectangleF(); 
descrRect.Width = 600; 
int measurement = ((int)graphicImage.MeasureString(header2, new Font("Gotham Medium", 28, FontStyle.Bold)).Height); 
var yindex = int.Parse(105 + header2Rect.Height.ToString()); 
descrRect.Location = new Point(30, 105+measurement); 
graphicImage.DrawString(description.ToLower(), new Font("Gotham", 24, FontStyle.Italic), SystemBrushes.WindowText, descrRect); 

(すなわちheader2が長いだけで1行があるとき。)が、私のmeasurement変数が唯一のフォントの高さは、全体ではなくDrawString矩形を測定します。高さがそのテキストに応じて変わるので、私は静的に高さを設定したくありません(header2Rect)。

header2Rect.Height = 0が原因でyindexが機能しません。 header2の行数を確認する方法はありますか?

MeasureStringの幅を境界矩形の幅で除算するだけで、次にMeasureStringの高さを乗算する必要がありますか?私は良い方法があると仮定しています。

おかげ

[EDIT]高さは実際には0であるように見えますが、テキストはすぐ外に溢れた、しかし幅はまだテキストの折り返しを収縮。私はちょうど高さを見つけるために数学計算をしましたが、よりよい方法があることを望みます。

答えて

6

あなたの四角形の高さを設定することはありません:

private void panel1_Paint(object sender, PaintEventArgs e) 
{ 
    string header2 = "This is a much, much longer Header"; 
    string description = "This is a description of the header."; 

    RectangleF header2Rect = new RectangleF(); 
    using (Font useFont = new Font("Gotham Medium", 28, FontStyle.Bold)) 
    { 
    header2Rect.Location = new Point(30, 105); 
    header2Rect.Size = new Size(600, ((int)e.Graphics.MeasureString(header2, useFont, 600, StringFormat.GenericTypographic).Height)); 
    e.Graphics.DrawString(header2, useFont, Brushes.Black, header2Rect); 
    } 

    RectangleF descrRect = new RectangleF(); 
    using (Font useFont = new Font("Gotham Medium", 28, FontStyle.Italic)) 
    { 
    descrRect.Location = new Point(30, (int)header2Rect.Bottom); 
    descrRect.Size = new Size(600, ((int)e.Graphics.MeasureString(description, useFont, 600, StringFormat.GenericTypographic).Height)); 
    e.Graphics.DrawString(description.ToLower(), useFont, SystemBrushes.WindowText, descrRect); 
    } 

} 
+0

あなたは素晴らしいです!これは私が探していたものです!ありがとう。 –

+0

私のC++プロジェクトでは、 'StringFormat :: GenericDypault()'の代わりに 'StringFormat :: GenericDefault()'だけが正しく動作します。理由は分かりません。 –

関連する問題