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

Evan Layman picture Evan Layman · Jul 19, 2011 · Viewed 13k times · Source

I am writing text over an image using Graphics DrawString method, binding my text with a RectangleF. Here is my code:

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

This works for some cases (ie. when header2 is only 1 line long), but my measurement variable only measures the height of the Font, not the whole DrawString rectangle. I do not want to set a static header2Rect height because the heights change depending on that text.

yindex does not work because header2Rect.Height = 0. Is there a way to see how many lines my header2 is?

Do I just need to do MeasureString width and divide that by my boundary rectangle width, then multiply by the MeasureString height? I'm assuming there is a better way.

Thanks

[EDIT] It looks like the height is actually 0 but the text just overflows outside, but the width still constricts the text-wrapping. I just did some math calculations to find the height, but I wish there was a better way.

Answer

LarsTech picture LarsTech · Jul 23, 2011

You are never setting your rectangle heights:

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

}