簡體   English   中英

C# Graphics.DrawString RectangleF 自動高度:如何找到該高度?

[英]C# Graphics.DrawString RectangleF Auto-Height: How to find that height?

我正在使用 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矩形。 我不想設置 static header2Rect高度,因為高度會根據該文本而變化。

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

我只需要做MeasureString寬度並將其除以我的邊界矩形寬度,然后乘以MeasureString高度嗎? 我假設有更好的方法。

謝謝

[編輯] 看起來高度實際上是 0,但文本只是溢出到外面,但寬度仍然限制了文本換行。 我只是做了一些數學計算來找到高度,但我希望有更好的方法。

您永遠不會設置矩形高度:

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);
  }

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM