C# 只在一个大面板中创建面板 我有这个代码(盒子大小随机生成):
//Set Location of panel
int xbox = r.Next(10, 766);
int ybox = r.Next(10, 390);
if(ybox + box.Height >= boxPanel.Location.Y + boxPanel.Height)
{
ybox = ybox - 100;
}
else if(xbox + box.Width >= boxPanel.Location.X + boxPanel.Width)
{
xbox = xbox - 100;
}
else if(xbox - box.Width <= boxPanel.Location.X - boxPanel.Width)
{
xbox = xbox + 100;
}
else if (ybox - box.Height <= boxPanel.Location.Y - boxPanel.Height)
{
ybox = ybox + 100;
}
box.Location = new Point(xbox, ybox);
我最终想要的是一个盒子或多个盒子,它们在面板中并且不在外面。我想在生成面板时看到它。我还想保留一个“不可见”的边界,这样它就不会在边缘产生。
答案 0 :(得分:0)
您不应该在这些语句中使用 else
;它们都应该是单独的 if
语句。如上所述,如果第一个 y
检查触发,则不会运行任何其他块/检查。
为什么不首先在正确的范围内随机生成 x
、y
值?
例如:
// assumes "box" was already created with a desired width/height
int xbox = r.Next(10, boxPanel.Width - box.Width - 10);
int ybox = r.Next(10, boxPanel.Height - box.Height - 10);
box.Location = new Point(xbox, ybox);
boxPanel.Controls.Add(box);
这将使框保持在另一个面板中,边缘周围有 10 像素的“边距”。