我试图让随机绘制的矩形在表单上彼此相邻排列,但我的循环不起作用并且给了我不想要的结果,任何帮助将不胜感激。
我已经创建了一个创建随机矩形并将它们存储在列表集合中的方法。
List<Rectangle> rectangleCollection = new List<Rectangle>();
void CreateRectangle()
{
int TallestRectangle = 0; ;
int PrevRecX = 0;
int PrevRecY = 0;
Pen pen = new Pen(Color.Black);
Graphics graphic = this.CreateGraphics();
foreach (Rectangle rect in rectangleCollection)
{
if (rect.Height > TallestRectangle)
TallestRectangle = rect.Height;
}
foreach (Rectangle rect in rectangleCollection)
{
if (PrevRecX + PrevRecY == 0)
{
graphic.DrawRectangle(pen, new Rectangle(rect.X, (TallestRectangle - rect.Height), rect.Width, rect.Height));
}
else
{
graphic.DrawRectangle(pen, new Rectangle((PrevRecX + PrevRecY), (TallestRectangle - rect.Height), rect.Width, rect.Height));
}
PrevRecX = rect.X;
PrevRecY = rect.Width;
}
}
void GetRandomRectangle()
{
Random ran = new Random();
int x = 0;
int y = 0;
int width = ran.Next(100, 500);
int height = ran.Next(200, 700);
Rectangle rec = new Rectangle(x, y, width, height);
rectangleCollection.Add(rec);
}