基于已知的cols和行绘制网格布局

时间:2014-11-03 18:12:36

标签: c# winforms

我想根据给定数量的已知方块绘制gridlayout。 例如,16个正方形,使8x8网格。 但我的网格看起来有点奇怪,无法帮助它:(

enter image description here

编辑:首先添加了错误的图片!

        int n = 16;
        int grid = (int)Math.Sqrt(n);
        int x = 0, y = 0;
        int yCounter = 0;
        int xCounter = 0;
        for (int i = 0; i < n; i++)
        {
            myGeometricObject[i] = new GeometricObject();

            x = xCounter * 50;
            xCounter++;


            if(i % grid == 0 && i > 0)
            {
                yCounter++;
                xCounter = 0;
                y = yCounter * 50;
            }

            myGeometricObject[i].Location = new System.Drawing.Point(x, y);
            myGeometricObject[i].Size = new System.Drawing.Size(50, 50);
            this.Controls.Add(myGeometricObject[i]);
        }

2 个答案:

答案 0 :(得分:1)

已解决,正确的代码如下所示

        int n = 16;
        int grid = (int)Math.Sqrt(n);
        int x = 0, y = 0;
        int yCounter = 0;
        int xCounter = 0;
        for (int i = 0; i < n; i++)
        {
            myGeometricObject[i] = new GeometricObject();

            if (i % grid == 0)
            {
                y = yCounter * 50;
                yCounter++;
                xCounter = 0;
            }
            else
            {
                xCounter++;
            }

            x = xCounter * 50;

            myGeometricObject[i].Location = new System.Drawing.Point(x, y);
            myGeometricObject[i].Size = new System.Drawing.Size(50, 50);
            this.Controls.Add(myGeometricObject[i]);
        }

答案 1 :(得分:0)

必须移动2行,如下所示:

    int n = 16;
    int grid = (int)Math.Sqrt(n);
    int x = 0, y = 0;
    int yCounter = 0;
    int xCounter = 0;
    for (int i = 0; i < n; i++)
    {
        myGeometricObject[i] = new GeometricObject();

        if(i % grid == 0 && i > 0)
        {
            yCounter++;
            xCounter = 0;
            y = yCounter * 50;
        }
        // Next 2 lines
        x = xCounter * 50;
        xCounter++;

        myGeometricObject[i].Location = new System.Drawing.Point(x, y);
        myGeometricObject[i].Size = new System.Drawing.Size(50, 50);
        this.Controls.Add(myGeometricObject[i]);
    }

哦,看到你自己解决了。总是很好!