我编写的代码用PictureBox
显示许多图像(100图像),但在运行应用程序时,只显示了一个图像......
请帮帮我们......
这是我的代码:
Random r = new Random();
private int randomPoint()
{
return 1 + r.Next() % 15;
}
// x0, y0
private int[] initialLocation = new int[2];
private void setLocation(int i)
{
int x0 = 50, y0=50;
initialLocation[1] = y0;
switch (i)
{
case 1: initialLocation[0] = x0;
break;
case 2: initialLocation[0] = x0 + 50;
break;
case 3: initialLocation[0] = x0 + 100;
break;
case 4: initialLocation[0] = x0 + 150;
break;
case 5: initialLocation[0] = x0 + 200;
break;
case 6: initialLocation[0] = x0 + 250;
break;
case 7: initialLocation[0] = x0 + 300;
break;
case 8: initialLocation[0] = x0 + 350;
break;
case 9: initialLocation[0] = x0 + 400;
break;
case 10: initialLocation[0] = x0 + 450;
break;
}
}
public Form1()
{
InitializeComponent();
PictureBox[] p = new PictureBox[10];
for (int i=0; i<10;i++)
{
p[i] = new PictureBox();
p[i].ImageLocation = "1.png";
int[] l = new int[2];
// create random location for images
setLocation(randomPoint());
p[i].Location = new Point(initialLocation[0], initialLocation[1]);
this.Controls.Add(p[i]);
}
}
答案 0 :(得分:6)
这是因为您每次想要图像时都会声明随机数生成器:
private int randomPoint()
{
Random r = new Random();
return 1 + r.Next() % 15;
}
将其替换为:
private Random r = new Random();
private int randomPoint()
{
return 1 + r.Next() % 15;
}
<强>更新强>
如果我理解正确,您希望在表单中以随机顺序显示15张图片。
为了确保您没有重复,您需要确保在选择下一个之前删除从列表中选择的图片。所以(在伪代码中)你需要这样的东西:
this.folderList = new List<string>();
// Populate it in an orderly manner
// Create temporary list to put the randomly selected items into
var radomisedList = new List<string>();
// Randomise the list.
var random = new Random();
int num = 0;
while (this.folderList.Count > 0)
{
num = random.Next(0, this.folderList.Count);
radomisedList.Add(this.folderList[num]);
this.folderList.RemoveAt(num);
}
这将确保您获得随机顺序而不会重复。