在彼此下面创建一个矩形

Creating Rectangles one under each other

我有一个程序可以根据我想要的数量创建特定数量的矩形。当我创建 1 个矩形时,高度为 400,当我创建 2 个矩形时,高度为 200,当我创建 4 个矩形时,高度为 100,我想你明白我在做什么。现在我想把它们放在一起。我举3个例子。

This is how it looks like when I create 1 Rectangle

当我想创建 2 个矩形时,高度应该除以 2。我已经这样做了,但我无法放置它们 like this under each other.

如果有人不明白我在尝试什么,再举一个例子。它应该是这样的 like when I create 5 Rectangles.

我试着把它们放在一起:

Canvas.SetLeft(MyRectangle[i], Width / 2.0 - MyRectangle[i].Width / 2.0);
Canvas.SetTop(MyRectangle[i], i * 120);

但这看起来 like this, it's not on top of the screen, and the other problem is that when I would want to create 2 it looks like this。所以我尝试在循环中使用 i 但我无法弄清楚任何事情。这是我的代码:

Brush brush = new SolidColorBrush(Color.FromRgb((byte)_random.Next(1, 255), (byte)_random.Next(1, 255), (byte)_random.Next(1, 255)));
        int howmanyrect = 3;
        Rectangle[] MyRectangle = new Rectangle[howmanyrect];

        if (howmanyrect == 1)
        {
            Rectangle OneRectangle = new Rectangle();

            OneRectangle.Fill = brush;
            OneRectangle.StrokeThickness = 2;
            OneRectangle.Stroke = Brushes.Black;
            OneRectangle.Width = 400;
            OneRectangle.Height = 400;

            Canvas.SetLeft(OneRectangle, Width / 2.0 - OneRectangle.Width / 2.0);
            Canvas.SetTop(OneRectangle, 30);

            myCanvas.Children.Add(OneRectangle);
            Content = myCanvas;
        }

       for (int i = 1; i <= howmanyrect - 1; i++)
        {
            MyRectangle[i] = new Rectangle
            {
                Fill = brush,
                StrokeThickness = 2,
                Stroke = Brushes.Black,
                Width = 400,
                Height = 400 / howmanyrect
            };
            
            Canvas.SetLeft(MyRectangle[i], Width / 2.0 - MyRectangle[i].Width / 2.0);
            Canvas.SetTop(MyRectangle[i], i * 120);

            myCanvas.Children.Add(MyRectangle[i]);
            Content = myCanvas;
        }

我尝试修复您的代码:

      Brush brush = new SolidColorBrush(Color.FromRgb((byte)_random.Next(1, 255), (byte)_random.Next(1, 255), (byte)_random.Next(1, 255)));
        int howmanyrect = 3;
        Rectangle[] MyRectangle = new Rectangle[howmanyrect];

        for (int i = 0; i < howmanyrect; i++)
        {
            var rectangle = new Rectangle
            {
                Fill = brush,
                StrokeThickness = 2,
                Stroke = Brushes.Black,
                Width = 400,
                Height = 400 / howmanyrect
            };
            MyRectangle[i] = rectangle;
        
            Canvas.SetLeft(rectangle, Width / 2.0 - rectangle.Width / 2.0);
            var distance = 10;
            Canvas.SetTop(rectangle, 30 + i * (400 / howmanyrect) + distance );
            myCanvas.Children.Add(rectangle);
        }
        Content = myCanvas;