通过单击按钮更改图片框阵列中的图像

时间:2019-05-26 23:09:41

标签: c# picturebox

我想通过单击按钮来生成和更改PictureBox数组中的图像。

这是我到目前为止尝试过的。

public Form1() {
     InitializeComponent();
 }

 PictureBox[] boxes = new PictureBox[6];

 private void GenerateButton1_Click(object sender, EventArgs e) {

     for (int i = 0; i < boxes.Length; i++) {
         boxes[i] = new PictureBox(); //set the pointer to a new PictureBox instance
         if (i == 0) boxes[i].Location = new System.Drawing.Point(3, 3);
         if (i == 1) boxes[i].Location = new System.Drawing.Point(221, 3);
         if (i == 2) boxes[i].Location = new System.Drawing.Point(439, 3);
         if (i == 3) boxes[i].Location = new System.Drawing.Point(3, 210);
         if (i == 4) boxes[i].Location = new System.Drawing.Point(221, 210);
         if (i == 5) boxes[i].Location = new System.Drawing.Point(439, 210);
         boxes[i].Size = new System.Drawing.Size(200, 200);
         boxes[i].Image = Image.FromFile(Application.StartupPath + "\\red.PNG"); //for setting its image

     }

     this.Controls.AddRange(boxes);
 }

 private void button1_Click(object sender, EventArgs e) {

     int i = 3;
     int signal = 1;
     boxes[i].SizeMode = PictureBoxSizeMode.StretchImage;
     if (signal == 0) boxes[i].Image = Image.FromFile(Application.StartupPath + "\\red.PNG");
     if (signal == 1) boxes[i].Image = Image.FromFile(Application.StartupPath + "\\green.PNG");
     if (signal == 2) boxes[i].Image = Image.FromFile(Application.StartupPath + "\\grey.PNG");
 }
 }
 }

通过单击button1,图像将根据条件从red.PNG变为green.PNG或grey.PNG,但是,我必须重做图像属性声明,例如boxes[i].SizeMode = PictureBoxSizeMode.StretchImage;。否则PictureBox将失去其属性。 有没有更简单的方法可以做到这一点。

谢谢。

0 个答案:

没有答案