在面板中间编写数字的最简单方法是什么?

时间:2013-06-15 22:58:40

标签: c# winforms

我在面板上有一系列面板和点击事件。最初我在面板中有标签,但它使得事情变得太杂乱并且使我的点击事件变得复杂。无论如何我只能在面板的中心写文字,因为在中间放置一个标签会干扰点击。我需要的是一个方形/矩形的对象,我可以a)停靠b)改变颜色c)将动态文本放在中间。也许我忽视了一个比小组更受欢迎的控件?

1 个答案:

答案 0 :(得分:3)

将Paint事件添加到Panel(s)并使用DrawString类的Graphics方法将数字绘制为字符串。请查看此代码作为示例:

//Add the Paint event, you can set the same handler for each panel you are using
panel1.Paint += new System.Windows.Forms.PaintEventHandler(this.panel1_Paint);

//create the font with size you want to use, measure the string with that font 
//and the Graphics class, calculate the origin point and draw your number:

 private void panel1_Paint(object sender, PaintEventArgs e)
 {
       Panel p = (Panel)sender;
       Font font = new System.Drawing.Font(new FontFamily("Times New Roman"),30);
       string number = "10";
       SizeF textSize = e.Graphics.MeasureString(number, font);
       PointF origin = new PointF(p.Width/2 - textSize.Width/2, p.Height/2 - textSize.Height/2);
       e.Graphics.DrawString("10", font, Brushes.Black, origin);
 }

由于此代码经常执行,您可能希望声明并实例化Font处理程序之外的Paint

 Font font = new System.Drawing.Font(new FontFamily("Times New Roman"),30);
 private void panel1_Paint(object sender, PaintEventArgs e)
 {
       Panel p = (Panel)sender;
       string number = "10";
       SizeF textSize = e.Graphics.MeasureString(number, font);
       PointF origin = new PointF(p.Width/2 - textSize.Width/2, p.Height/2 - textSize.Height/2);
       e.Graphics.DrawString("10", font, Brushes.Black, origin);
 }

编辑:

在OP的评论后添加: 找到字符串仍然适合Panel的最大字体大小

string number = "10";
float emSize = 10f;
SizeF textSize = SizeF.Empty;
Font font = null;
do
{
     emSize++;
     font = new System.Drawing.Font(new FontFamily("Times New Roman"), emSize);
     textSize = e.Graphics.MeasureString(number, font);
}
while (panel1.Width > textSize.Width && panel1.Height > textSize.Height);
font = new System.Drawing.Font(new FontFamily("Times New Roman"), --emSize);

免责声明:我没有考虑floatint投射,但这也应该得到解决。