2014-11-03 29 views
0

我想根据给定的已知数量的正方形绘制网格布局。 例如,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]); 
     } 
+0

'例如,16格,使得8x8格。“ - 犯错....什么? 8 * 8 == 64,而不是16 ... – 2014-11-03 18:21:27

+0

另外,使用WPF,这成为一行:''。忘记无用的winforms,这迫使你重新发明一切。 – 2014-11-03 18:22:38

+0

由于测试,sry改变了我的例子,在这种情况下,它的4,sry – fubbe 2014-11-03 18:24:25

回答

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

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

+0

无论如何给你一个upVote :) – fubbe 2014-11-03 18:48:35

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