碰撞图片框,随机位置无法正常工作

时间:2016-01-19 20:02:52

标签: c# arrays picturebox overlap overlapping

我一直试图制作一个在空间中随机创建的图像数组,事情就是当它们重叠时,它们不会改变它们的位置。

    int number;

    PictureBox[] X = new PictureBox[100]; 

    public Form1()
    {
        InitializeComponent();
    }

    private void addX(int number)
    {
        Random randomNumber = new Random(DateTime.Now.Millisecond);
        int x = randomNumber.Next(0, reprezentare.Height - 40);
        int y = randomNumber.Next(0, reprezentare.Width - 40);
        X[number] = new PictureBox();
        X[number].Height = 41;
        X[number].Width = 41;
        X[number].SizeMode = PictureBoxSizeMode.Zoom;
        X[number].Image = Properties.Resources.X;

        if(number >= 1)
        {
            while (pictureBox1.Bounds.IntersectsWith(X[number - 1].Bounds)) x = randomNumber.Next(0, reprezentare.Height - 40);
            while (pictureBox1.Bounds.IntersectsWith(X[number - 1].Bounds)) y = randomNumber.Next(0, reprezentare.Width - 40);
        }

        X[number].Location = new Point(x, y);
        reprezentare.Controls.Add(X[number]);
        number++;

        richTextBox1.Text += x + " : " + y;
        richTextBox1.Text += Environment.NewLine;
    }

    private void button1_Click(object sender, EventArgs e)
    {
        addX(number);
    }

有谁知道如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

一些问题。首先,您有一个变量number和一个参数number。不好:

int number;
private void addX(int number)

只需将其更改为:

private void addX()

其次,您只是在与PictureBox1进行比较,因此您添加的所有PictureBox都没有检查其他PictureBox,因此您可以尝试这样的事情:

bool ok = false;
while (!ok) {
  ok = true;
  int x = randomNumber.Next(0, reprezentare.Width - 40);
  int y = randomNumber.Next(0, reprezentare.Height - 40);
  for (int i = 0; i < number; ++i) {
    if (X[i].Bounds.IntersectsWith(new Rectangle(x, y, 41, 41))) {
      ok = false;
      break;
    }
  }
  if (ok) {
    X[number].Location = new Point(x, y);
  }
}
reprezentare.Controls.Add(X[number]);
number++;

您必须添加一项检查以查看是否仍有空间可用,以避免循环进入无穷大。