我有一系列面板和面板上的点击事件。最初我在面板中有标签,但它使我的点击事件变得过于混乱和复杂。无论如何我可以在面板的中心写文本,因为在中间放置一个标签会干扰点击。我只需要一个方形/矩形对象,我可以 a) 停靠 b) 更改颜色 c) 将动态文本放在中间。也许我忽略了一个比面板更可取的控件?
问问题
226 次
1 回答
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 的评论之后添加:查找字符串仍适合面板的最大字体大小
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);
免责声明:我没有考虑float
到int
选角,但这也是应该注意的。
于 2013-06-15T23:11:02.270 回答