划分并绘制多个矩形

时间:2016-04-08 11:14:33

标签: c# winforms graphics

我有一个这样的矩形Rectangle Rect = new Rectangle(0, 0, 300, 200); 我想把它平均分成20个矩形5X4(5列,4行)这样

|'''|'''|'''|'''|'''|
|...|...|...|...|...|
|'''|'''|'''|'''|'''|
|...|...|...|...|...|
|'''|'''|'''|'''|'''|
|...|...|...|...|...|
|'''|'''|'''|'''|'''|
|...|...|...|...|...|

Cn有人帮忙吗?我一直试图解决这个问题一小时:(

2 个答案:

答案 0 :(得分:1)

要创建20个矩形的列表(就像你想要的那样),你可以使用它:

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

答案 1 :(得分:1)

这应该有所帮助:

给出你的矩形:

    Rectangle Rect = new Rectangle(0, 0, 300, 200);

这将获得子矩形列表:

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

请注意,返回RectangleF而不是Rectangle以避免精度损失。当你需要Rectangle时,你总能得到一个这样的:

 Rectangle rec = Rectangle.Round(srex[someIndex]);