我已经覆盖了 OnPaint我的方法Label 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);
}
}
这行得通,但我真的很想知道如何使文本垂直和水平居中。我听说过 MeasureString()
方法,但我的“文本”使事情变得复杂,因为它可能包含分页符。
有人可以指导我如何做到这一点吗?
最佳答案
或者,您可以创建自己的 StringFormat
对象,并使用支持 RectangleF 的 DrawString
重载将其传递:
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);
关于c# - 用于在 System.Label 上准确放置文本的图形 DrawString,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2593675/