1

我有一个简单的表格,里面有 10 个图片框,例如:pictureBox1, pictureBox2, pictureBox3...

我有一个包含 10 张图片的文件夹,例如: image1, image2, image3...

现在我很聪明,知道我不想硬编码pictureBox1.ImageLocation = image1pictureBox2.ImageLocation = image2......相反,我需要创建某种循环或数组,用它们各自的图像填充我的图片框,但我不够聪明弄清楚如何。

就像是:

for (int i = 0; i < 10; i++)
{
    pictureBox[i].ImageLocation = image[i];
}

最终,我希望这个项目能够动态扩展,如果我有一个包含 12 个图像的文件,程序将简单地创建 12 个图片框并加载图像。一点帮助会很棒。

4

1 回答 1

0

尽管我建议列出一个清单,但您在那里拥有的东西会很粗糙。

List<PictureBox> pictureBoxes = new List<PictureBox>();
List<Image> images = new List<Image>();

//code to populate your lists

for (int i = 0; i < pictureBoxes.Count; i++)
{
    pictureBoxes[i].Image = images[i];
}

如果您想确保PictureBox列表中有足够的图像,您可以提前检查:

if (images.Count >= pictureBoxes.Count)
{
    for (int i = 0; i < pictureBoxes.Count; i++)
    {
        pictureBoxes[i].Image = images[i];
    }
}

...或者在图像用完之前尽可能多地填写。

for (int i = 0; i < pictureBoxes.Count && i < images.Count; i++)
{
    pictureBoxes[i].Image = images[i];
}


编辑:因此,如果您想使用字符串来设置图像的位置,则可以这样做。看一下这个:

  List<PictureBox> pictureBoxes = new List<PictureBox>();
  List<string> imageLocations = new List<string>();

  private void Form1_Load(object sender, EventArgs e)
  {
     PictureBox PB1 = new PictureBox();
     PB1.Location = new Point(0, 0);
     PB1.Size = new Size(144, 197);
     Controls.Add(PB1);
     PictureBox PB2 = new PictureBox();
     PB2.Location = new Point(145, 0);
     PB2.Size = new Size(327, 250);
     Controls.Add(PB2);

     pictureBoxes.Add(PB1);
     pictureBoxes.Add(PB2);

     imageLocations.Add(@"C:\PicExample\image1.jpg");
     imageLocations.Add(@"C:\PicExample\image2.jpg");

     for (int i = 0; i < pictureBoxes.Count && i < imageLocations.Count; i++)
     {
        pictureBoxes[i].ImageLocation = imageLocations[i];
     }
  }

图片!


编辑迭代创建PictureBoxe列表:

如果您不想担心对列表进行硬编码(并且您的图片框大小相同),您可以执行以下操作:

 for (int i = 0; i < HoweverManyPictureBoxesYouWant; i++)
 {
    PictureBox PB = new PictureBox();
    PB.Name = "PB" + i.ToString();
    PB.Location = new Point(250 * i, 0); //Edit this as you see fit for location, i'm just putting them in a row
    PB.Size = new Size(250, 250);
    PB.ImageLocation = @"C:\PicExample\image" + i.ToString() + ".jpg";
    Controls.Add(PB);
    pictureBoxes.Add(PB); //You only need to do this if you want the PB's in a list for other reasons than setting the image location
 }
于 2013-07-24T21:10:52.727 回答