gpt4 book ai didi

c# - 如何让图片框不重叠?

转载 作者:行者123 更新时间:2023-12-05 04:36:51 27 4
gpt4 key购买 nike

所以我在 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 类的 IntersectWith 方法

https://learn.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))

关于c# - 如何让图片框不重叠?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70772673/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com