2011-07-19 56 views
5

我正在使用Graphics DrawString方法將圖像寫入圖像,並使用RectangleF綁定我的文本。這裏是我的代碼:C#Graphics.DrawString RectangleF自動高度:如何找到那個高度?

//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矩形。我不想設置靜態高度,因爲高度根據文本而改變。

yindex不起作用,因爲header2Rect.Height = 0。有沒有辦法查看我的header2有多少行?

我只需要做MeasureString寬度和除以我的邊界矩形寬度,然後乘以MeasureString高度?我假設有一個更好的方法。

感謝

[編輯]它看起來像的高度實際上是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 :: GenericDefault()'可以正常工作,而不是'StringFormat :: GenericTypographic()'。我不確定是什麼原因。 –