views:

529

answers:

2

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

void Label_OnPaint(object sender, PaintEventArgs e) {
  base.OnPaint(e);
  Label 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?

+1  A: 

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

SLaks
You also have to use the overload that takes a `Rectangle`.
Aaronaught
TrueType hinting is liable to ruin the shadow effect.
Hans Passant
@SLaks: How would I get the DeviceContext (first parameter) for a System.Label object?
jp2code
Pass `e.Graphics` from the `Paint` event handler. (`Graphics` implements `IDeviceContext`)
SLaks
+1  A: 

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);
Ron Warholic
Both are answers, but I can only mark one. This one has code for others to follow up with.
jp2code