我尝试将12个图片框中的0到11的文字放在一个球形图像上,但是所有文本都是11。
如何从0到11获取球上的文字?
这是我的代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace wfballs2
{
public partial class Form1 : Form
{
String s;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
PictureBox[] Shapes = new PictureBox[12];
for (int i = 0; i < 12; i++)
{
s = Convert.ToString(i);
Shapes[i] = new PictureBox();
Shapes[i].Name = "ball" + i.ToString();
Shapes[i].Location = new Point(10 + 45 * i, 300);
Shapes[i].Size = new Size(40, 40);
Shapes[i].Image = Image.FromFile(@ "C:\Users\Eiko\Desktop\ball\ball.jpg");
Shapes[i].SizeMode = PictureBoxSizeMode.CenterImage;
Shapes[i].Visible = true;
this.Controls.Add(Shapes[i]);
Shapes[i].Paint += new PaintEventHandler((sender2, e2) =>
{
e2.Graphics.DrawString(s, Font, Brushes.Black, 10, 13);
});
}
}
}
}
答案 0 :(得分:1)
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace wfballs2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
int k = 0;
PictureBox[] Shapes = new PictureBox[12];
for (int i = 0; i < 12; i++)
{
Shapes[i] = new PictureBox();
Shapes[i].Name = "ball" + i.ToString();
Shapes[i].Location = new Point(10 + 45 * i, 300);
Shapes[i].Size = new Size(40, 40);
Shapes[i].Image = Image.FromFile(@ "C:\Users\Eiko\Desktop\ball\ball.jpg");
Shapes[i].SizeMode = PictureBoxSizeMode.CenterImage;
Shapes[i].Visible = true;
this.Controls.Add(Shapes[i]);
Shapes[i].Paint += new PaintEventHandler((sender2, e2) =>
{
e2.Graphics.DrawString(k.ToString(), Font, Brushes.Black, 10, 13);
k++;
});
}
}
}
}
答案 1 :(得分:1)
变量s
是表单中的一个实例,因此它的值由表单和您创建的所有形状共享。
每当你的一个形状被涂上时,这段代码:
e2.Graphics.DrawString(s, Font, Brushes.Black, 10, 13);
会运行。 s
是表单的实例变量。它将为所有形状显示它设置的最后一个值。在你的情况下,你的for循环的最后一次迭代发生,因此11。
要解决此问题,您必须在匿名事件处理程序之前捕获局部变量中的循环变量,然后使用该局部变量在事件处理程序中执行Convert.ToString(val)
,如下所示:
var val = i; // capture variable
Shapes[i].Paint += new PaintEventHandler((sender2, e2) =>
{
// use captured variable here
e2.Graphics.DrawString(Convert.ToString(val), Font, Brushes.Black, 10, 13);
});
这将生成基于val
的局部变量的字符串。