6

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静的な高さを設定したくありません。header2Rect

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

幅を実行しMeasureString、それを境界矩形の幅で割り、MeasureString高さを掛けるだけですか? もっと良い方法があると思います。

ありがとう

[編集] 高さは実際には 0 のように見えますが、テキストは外側にはみ出していますが、幅は依然としてテキストの折り返しを制限しています。高さを見つけるためにいくつかの数学計算を行っただけですが、もっと良い方法があればいいのにと思います。

4

1 に答える 1

14

長方形の高さを設定することはありません:

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

}
于 2011-07-22T23:03:04.400 に答える