我想同时显示四个图像,并在表单加载时切换图像。目前,图像将以不同的数字显示,例如:将出现1个图像或2个图像,等等4.我还要确保不会出现重复。
Form1_Load中的代码:
PictureBox[] boxes = new PictureBox[4];
boxes[0] = pictureBox0;
boxes[1] = pictureBox1;
boxes[2] = pictureBox2;
boxes[3] = pictureBox3;
for (int i = 0; i < boxes.Length; i++)
{
int switcher = r.Next(0, 5);
switch (switcher)
{
case 0:
{ boxes[i].Image = Properties.Resources.dog0; } break;
case 1:
{ boxes[i].Image = Properties.Resources.dog1; } break;
case 2:
{ boxes[i].Image = Properties.Resources.dog2; } break;
case 3:
{ boxes[i].Image = Properties.Resources.dog3; } break;
}
}
更新 - 工作
程序现在在加载时移动图像并且没有重复:)
List<Bitmap> resources = new List<Bitmap>();
resources.Add(Properties.Resources.dog0);
resources.Add(Properties.Resources.dog1);
resources.Add(Properties.Resources.dog2);
resources.Add(Properties.Resources.dog3);
resources = resources.OrderBy(a => Guid.NewGuid()).ToList();
for (int i = 0; i < resources.Count; i++)
{
pictureBox0.Image = resources[0];
pictureBox1.Image = resources[1];
pictureBox2.Image = resources[2];
pictureBox3.Image = resources[3];
}
上面给出的两个例子显示了它现在发生了什么。
答案 0 :(得分:1)
正如M.kazem Ahkhary指出你需要改变图像:
List<Bitmap> resources = new List<Bitmap>();
resources.Add(Properties.Resources.dog0);
resources.Add(Properties.Resources.dog1);
resources.Add(Properties.Resources.dog2);
resources.Add(Properties.Resources.dog3);
resources = resources.OrderBy(a => Guid.NewGuid()).ToList(); // Dirty but effective shuffle method
pictureBox0.Image = resources[0];
pictureBox1.Image = resources[1];
pictureBox2.Image = resources[2];
pictureBox3.Image = resources[3];
答案 1 :(得分:1)
实施非常简单。首先,您需要对数组进行混洗,然后迭代它。 Fisher–Yates shuffle
创建方法ShuffleImages
,如下所示:
public void ShuffleImages(PictureBox[] img)
{
Random r = new Random();
for (int i = 0; i < img.Length - 1; i++)
{
int j = r.Next(i, img.Length);
PictureBox temp = img[j];
img[j] = img[i];
img[i] = temp;
}
}
并在Form1_Load
事件中调用该方法:
private void Form1_Load(object sender, EventArgs e)
{
PictureBox[] boxes = new PictureBox[4];
boxes[0] = pictureBox0;
boxes[1] = pictureBox1;
boxes[2] = pictureBox2;
boxes[3] = pictureBox3;
ShuffleImages(boxes); //call the method
for (int i = 0; i <= 3; i++)
{
switch (i)
{
case 0:
{ boxes[i].Image = Properties.Resources.dog0; }
break;
case 1:
{ boxes[i].Image = Properties.Resources.dog1; }
break;
case 2:
{ boxes[i].Image = Properties.Resources.dog2; }
break;
case 3:
{ boxes[i].Image = Properties.Resources.dog3; }
break;
}
}
}