如何让图片框彼此不重叠

  • 本文关键字:重叠 c# .net winforms
  • 更新时间 :
  • 英文 :


所以我用windows窗体为一个学校项目制作了一个游戏。唯一的问题是,我的照片互相重叠。所以我的问题是,我如何让它们都在不同的位置,在那里它们不会相互接触或重叠?

在这个方法中,我创建僵尸,在这里我只选择在-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];
}
}

僵尸重叠的图片

跟踪已经放置的图片框,并验证绑定是否会重叠。

//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类的IntersectWith方法

https://learn.microsoft.com/en-us/dotnet/api/system.drawing.rectangle.intersectswith?view=net-6.0#系统图矩形交叉开关(系统图矩形(

编辑:

这里是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];
}
}

相关内容

  • 没有找到相关文章

最新更新