-2

我的输入正确完成,我的所有矩形都垂直堆叠,每次绘制新矩形时都有不同的颜色,但我很难让输出看起来像底部图片。请任何人都可以帮助我走上正确的道路。

矩形

    //List to strore all randomly generated rectangles
    List<Rectangle> rectangleCollection = new List<Rectangle>();
    //Counts the amount of time a rectangle needs to be drawn
    int count = 0;

    public static Random ran = new Random();

    void CreateRectangle()
    {
        int TallestRectangle = 0; ;


        int PrevRecY = 0;

        Graphics graphic = pictureBox1.CreateGraphics();
        SolidBrush brush;

        foreach (Rectangle rect in rectangleCollection)
        {
            if (rect.Height > TallestRectangle)
                TallestRectangle = rect.Height;
        }

        foreach (Rectangle rect in rectangleCollection)
        {
            graphic.FillRectangle(brush = new SolidBrush(Color.FromArgb(ran.Next(1, 255), ran.Next(1, 255), ran.Next(1, 255))),
                new Rectangle(rect.X + PrevRecY, (TallestRectangle - rect.Height), rect.Width, rect.Height));

            PrevRecY += rect.Width;
        }
    }

    private void button1_Click(object sender, EventArgs e)
    {
        count = int.Parse(textBox1.Text);
        for (int i = 0; i < count; i++)
        {
            GetRandomRectangle();
        }
        CreateRectangle();
    }

    void GetRandomRectangle()
    {
        Graphics graph = this.CreateGraphics();
        int x = 0;
        int y = 0;

        int width = ran.Next(20, 100);
        int height = ran.Next(30, 150);

        Rectangle rec1 = new Rectangle(x, y, width, height);
        rectangleCollection.Add(rec1);
    }
4

1 回答 1

2

对于每个矩形,从最短到最高排序,

  • 制作一个该高度的水平矩形,从所有高于该高度的矩形的左侧开始,到该高度右侧的所有矩形的右侧结束。

每当您创建一个水平矩形时,将其放置在您正在创建的矩形下方(就水平位置而言)的最高水平矩形的顶部。

于 2013-04-25T10:39:38.457 回答