1

我试图让随机绘制的矩形在表单上彼此相邻排列,但我的循环不起作用并且给了我不想要的结果,任何帮助将不胜感激。

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

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

1 回答 1

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

  // ...
}
于 2013-04-25T07:55:28.707 回答