Reputation: 510
I have a rectangle like this Rectangle Rect = new Rectangle(0, 0, 300, 200);
and i want to divide it equaly in 20 rectangles 5X4 (5 Columns, 4 Rows) like this
|'''|'''|'''|'''|'''|
|...|...|...|...|...|
|'''|'''|'''|'''|'''|
|...|...|...|...|...|
|'''|'''|'''|'''|'''|
|...|...|...|...|...|
|'''|'''|'''|'''|'''|
|...|...|...|...|...|
Cn anyone help? Ive been trying solve this for like an hour :(
Upvotes: 0
Views: 437
Reputation: 54453
This should help:
Given your rectangle:
Rectangle Rect = new Rectangle(0, 0, 300, 200);
This will get a list of subrectangles:
List<RectangleF> GetSubRectangles(Rectangle rect, int cols, int rows)
{
List<RectangleF> srex = new List<RectangleF>();
float w = 1f * rect.Width / cols;
float h = 1f * rect.Height / rows;
for (int c = 0; c < cols; c++)
for (int r = 0; r < rows; r++)
srex.Add(new RectangleF(w*c, h*r, w,h ));
return srex;
}
Note that is returns RectangleF
not Rectangle
to avoid loss of precision. When you need a Rectangle
you can always get one like this:
Rectangle rec = Rectangle.Round(srex[someIndex]);
Upvotes: 1
Reputation: 7666
To create a list of 20 rectangles (like you want it) you could use this:
List<Rectangle> list = new List<Rectangle>();
int maxWidth = 300;
int maxHeight = 200;
int x = 0;
int y = 0;
while (list.Count < 20)
{
for (x = 0; x < maxWidth; x += (maxWidth / 5))
{
for (y = 0; y < maxHeight; y += (maxHeight / 4))
{
list.Add(new Rectangle(x, y, (maxWidth / 5), (maxHeight / 4));
}
y = 0;
}
x = 0;
}
Upvotes: 2