如何将随机绘制的矩形垂直堆叠在一起?

时间:2013-04-25 07:00:00

标签: c# winforms graphics

我试图让随机绘制的矩形在表格上彼此相邻排列但是我的循环不起作用并且给我不希望的结果,任何帮助都将非常感激。

我已经创建了一个创建随机矩形的方法,然后将它们存储在列表集合中。

    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);
    }

1 个答案:

答案 0 :(得分:0)

你的第二个foreach看起来太复杂了。我认为你真的不需要PrevRecX。试试这个,看看它是否符合你的期望。

void CreateRectangle()
{
  int TallestRectangle = 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)
  {
    graphic.DrawRectangle(pen, new Rectangle(rect.X + PrevRecY, (TallestRectangle - rect.Height), rect.Width, rect.Height));
    PrevRecY += rect.Width; // note the +=
  }
}

至于static Random,只需在方法外声明变量并在里面使用它,就像那样:

private static Random ran = new Random();
void GetRandomRectangle()
{
  int x = 0;
  int y = 0;

  int width = ran.Next(100, 500);
  int height = ran.Next(200, 700);

  // ...
}