I have a program that creates a specific number of rectangles according to how many I want. When I create 1 Rectangle the Height is 400 when I create 2 Rectangles then the height is 200 when I create 4 Rectangles the height is 100, I think you understand what I'm doing. Now I want to place them one under each other. I give you 3 examples.
This is how it looks like when I create 1 Rectangle
And when I want to create 2 Rectangles the height should get divided by 2. I already did that and that's working but I can't place them like this under each other.
Only one more example if someone doesn't understand what I'm trying. This is how it should look like when I create 5 Rectangles.
I tried putting them under each other like that:
Canvas.SetLeft(MyRectangle[i], Width / 2.0 - MyRectangle[i].Width / 2.0);
Canvas.SetTop(MyRectangle[i], i * 120);
But that looks 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. So I tried around with using i from the loop but I can't figure anything out. This is my code:
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;
}
CodePudding user response:
I try to fix your code :
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;