Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Graphics DrawString to Exactly Place Text on a System.Label

I have overridden the OnPaint method of my Label control in VS2008:

void Label_OnPaint(object sender, PaintEventArgs e) {
  base.OnPaint(e);
  dim lbl = sender as Label;
  if (lbl != null) {
    string Text = lbl.Text;
    e.Graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
    if (myShowShadow) { // draw the shadow first!
      e.Graphics.DrawString(Text, lbl.Font, new SolidBrush(myShadowColor), myShadowOffset, StringFormat.GenericDefault);
    }
    e.Graphics.DrawString(Text, lbl.Font, new SolidBrush(lbl.ForeColor), 0, 0, StringFormat.GenericDefault);
  }
}

This works, but I really want to find out how to center the text both vertically and horizontally. I've heard of the MeasureString() method, but my "Text" complicates matters because it could include page breaks.

Could someone guide me with how to do this?

like image 348
jp2code Avatar asked Dec 08 '22 03:12

jp2code


2 Answers

Alternatively you can create your own StringFormat object and pass it in using an overload of DrawString that supports a RectangleF:

StringFormat formatter = new StringFormat();
formatter.LineAlignment = StringAlignment.Center;
formatter.Alignment = StringAlignment.Center;

RectangleF rectangle = new RectangleF(0, 0, lbl.Width, lbl.Height);

e.Graphics.DrawString(Text, lbl.Font, new SolidBrush(lbl.ForeColor), rectangle, formatter);
like image 163
Ron Warholic Avatar answered Dec 09 '22 16:12

Ron Warholic


You can call TextRenderer.DrawText with the HorizontalCenter and VerticalCenter flags.

like image 32
SLaks Avatar answered Dec 09 '22 18:12

SLaks