C# Button text 重写时,字不居中
从不签到 2009-03-06 01:03:54 如题
重写button,使每个字的颜色不同
主要代码如下
protected override void OnPaint(PaintEventArgs pe)
{
Graphics g = pe.Graphics;
base.OnPaint(pe); //调用父控件的方法
string strA = "ABCD";
SizeF txtSize = g.MeasureString(strA, this.Font);
char[] cOutput = strA.ToCharArray();
int iLength = strA.Length;
DrawButtonText(g, cOutput, txtSize, iLength);
}
//重画Button的文本(Text),不使用图案填充
private void DrawButtonText(Graphics dbg,char[] txt, SizeF siz, int len)
{
int wid = (int)(siz.Width / len); //每个字的长度
StringFormat format = new StringFormat();
format.LineAlignment = StringAlignment.Center;//居中
format.Alignment = StringAlignment.Center;//居中
//button的长度减去字符总的长度,然后/2就是第一个字母的x坐标,y一样
Single x = (this.Width - siz.Width) / 2;
//Y position
Single y = (this.Height - siz.Width) / 2;
dbg.DrawString(txt[0].ToString(), this.Font, new SolidBrush(Color.Red), x, y, format);
dbg.DrawString(txt[1].ToString(), this.Font, new SolidBrush(Color.Black), x + wid, y, format);
dbg.DrawString(txt[2].ToString(), this.Font, new SolidBrush(Color.Pink), x + wid * 2, y, format);
dbg.DrawString(txt[3].ToString(), this.Font, new SolidBrush(Color.Green), x + wid * 3, y, format);
}
但是结果是,字符偏左,偏上
哪里不对?请指正,谢谢。