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);
}

但是结果是,字符偏左,偏上
哪里不对?请指正,谢谢。
...全文
360 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
从不签到 2009-03-06
  • 打赏
  • 举报
回复
谢谢了!
steal8275756 2009-03-06
  • 打赏
  • 举报
回复
问题搞定 你画的时候别用fomat这个参数就行了


dbg.DrawString(txt[0].ToString(), this.Font, new SolidBrush(Color.Red), x, y);
dbg.DrawString(txt[1].ToString(), this.Font, new SolidBrush(Color.Black), x + wid, y);
dbg.DrawString(txt[2].ToString(), this.Font, new SolidBrush(Color.Blue), x + wid * 2, y);
dbg.DrawString(txt[3].ToString(), this.Font, new SolidBrush(Color.Green), x + wid * 3, y);
从不签到 2009-03-06
  • 打赏
  • 举报
回复
2楼
我的button重写了,就是位置判断不准阿
从不签到 2009-03-06
  • 打赏
  • 举报
回复
我写错了,代码确实如沙发那样写的,
但是不行
99 2009-03-06
  • 打赏
  • 举报
回复
沙发强悍!
whowhen21 2009-03-06
  • 打赏
  • 举报
回复
你那绘制图形和给Button 的Text赋值是不相同的,Text赋值可以用这个属性:
button1.TextAlign = ContentAlignment.MiddleCenter;

绘制图形可能要根据位置判断呀!
tweeger 2009-03-06
  • 打赏
  • 举报
回复
这一句代码:“Single y = (this.Height - siz.Width) / 2;”
修改为:“Single y = (this.Height - siz. Height) / 2;”
应该就可以了,小错误哦!lz要细心了。

110,533

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧