图形DrawString将文本正确放置在System.Label上

jp2*_*ode 4 c# graphics onpaint

我在VS2008中覆盖了我的Label控件的OnPaint方法:

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);
  }
}
Run Code Online (Sandbox Code Playgroud)

这有效,但我真的想知道如何垂直和水平居中文本.我听说过这种MeasureString()方法,但是我的"文本"使问题变得复杂,因为它可能包含分页符.

有人可以指导我如何做到这一点?

Ron*_*lic 9

或者,您可以创建自己的StringFormat对象并使用DrawString支持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);
Run Code Online (Sandbox Code Playgroud)


Neo*_*Neo 2

这是我目前正在使用的代码,

SizeF size;
string text = "Text goes here";
size = e.Graphics.MeasureString(text, font);
x = (lineWidth / 2) - (size.Width / 2);
y = top;
e.Graphics.DrawString(text, font, Brushes.Black, x, y);
Run Code Online (Sandbox Code Playgroud)