如何让图片框不重叠?

How to let pictureboxes not overlap with each other?

所以我以 windows 形式为学校项目制作了一个游戏。唯一的问题是,我的照片相互重叠。所以我的问题是如何将它们全部放在彼此不接触或不重叠的不同位置?

在这个方法中,我创建了僵尸,这里我只是选择 x-as 上 -100 和 0 之间的随机位置

public void ZombieMaker(int aantal, Form formInstance, string ZombieDik)
{
    for (int i = 0; i < aantal; i++)
    {
            PictureBox picture = new PictureBox();

            picture.Image = Properties.Resources.ZombieDik;
            picture.Size = new Size(200, 200);
            picture.Location = new Point(random.Next(1500), random.Next(-100,0));
            picture.SizeMode = PictureBoxSizeMode.Zoom;
            picture.Click += zombie_Click;
            picture.BackColor = Color.Transparent;
            formInstance.Controls.Add(picture);
            picture.Tag = zombies[i];
    }
}

pic of zombies overlapping

跟踪已放置的图片框,并验证边界是否会重叠。

//List of all pictureBoxes
private List<PictureBox> _pictureBoxes = new List<PictureBox>();

public void ZombieMaker(int aantal, Form formInstance, string ZombieDik)
{
    for (int i = 0; i < aantal; i++)
    {
        Rectangle newPosition;

        //loop till you found a new position
        while (true)
        {
            var newPoint = new Point(random.Next(1500), random.Next(-100,0));
            var newSize = new Size(200, 200);

            newPosition = new Rectangle(newPoint, newSize);

            //validate the newPosition
            if (!_pictureBoxes.Any(x => x.Bounds.IntersectsWith(newPosition)))
            {
                //break the loop when there isn't an overlapping rectangle found
                break;
            }
        }

        PictureBox picture = new PictureBox();
        _pictureBoxes.Add(picture);
 
        picture.Image = Properties.Resources.ZombieDik;
        picture.Size = newPosition.Size;
        picture.Location = newPosition.Location;
        ...
      
    }
}

为了验证重叠,我正在使用 Rectangle class

IntersectWith 方法

https://docs.microsoft.com/en-us/dotnet/api/system.drawing.rectangle.intersectswith?view=net-6.0#system-drawing-rectangle-intersectswith(system-drawing-rectangle)

编辑:

这里是 do/while 循环而不是 while 循环。

Rectangle newPosition;

do
{
    var newPoint = new Point(random.Next(1500), random.Next(-100,0));
    var newSize = new Size(200, 200);

    newPosition = new Rectangle(newPoint, newSize);
} while(_pictureBoxes.Any(x => x.Bounds.IntersectsWith(newPosition))

我修正了你的代码,所以图片框不会相互重叠:

public void ZombieMaker(int aantal, Form formInstance, string ZombieDik)
{
   for (int i = 0; i < aantal; i++)
   {
        PictureBox picture = new PictureBox();

        picture.Image = Properties.Resources.ZombieDik;
        picture.Size = new Size(200, 200);
        picture.Location = new Point(picture.Width * i, random.Next(-100,0));
        picture.SizeMode = PictureBoxSizeMode.Zoom;
        picture.Click += zombie_Click;
        picture.BackColor = Color.Transparent;
        formInstance.Controls.Add(picture);
        picture.Tag = zombies[i];
  }
}