如何使这个正方形网格居中?

时间:2019-01-28 18:44:34

标签: geometry processing

我试图简单地生成5个旋转矩形的网格。但是网格不会居中显示。有人可以帮我吗?

int margin = 150; //padding to sides and top/bottom
int rectH = 60; // height of rectangle 
int rectW = 20; //  width of rectangle 
int n_rectangles = 5; // 5 rectangles to draw

size(800,800);
for (int x =  margin+rectW; x <= width - margin; x += (width-2*(margin+rectW))/n_rectangles) {
  for (int y =  margin+rectH; y <= height - margin; y += (height-2*(margin+rectH))/n_rectangles) {
     fill(255);
     //now rotate matrix 45 degrees
     pushMatrix();
     translate(x, y);
     rotate(radians(45));
     // draw rectangle at x,y point
     rect(0, 0, rectW, rectH);
     popMatrix();

  }
}

1 个答案:

答案 0 :(得分:1)

我建议绘制一个“居中”的矩形,矩形的原点为(-rectW/2, -rectH/2)

rect(-rectW/2, -rectH/2, rectW, rectH);

针对行和列,计算第一个矩形中心到最后一个矩形中心的距离:

int size_x = margin * (n_rectangles-1); 
int size_y = margin * (n_rectangles-1); 

翻译到屏幕(width/2, height/2)的中心,
到左上方矩形(-size_x/2, -size_y/2)
的位置 最后将每个矩形移到其位置(i*margin, j*margin)

translate(width/2 - size_x/2 + i*margin, height/2 - size_y/2 + j*margin);

查看最终代码:

int margin = 150; //padding to sides and top/bottom
int rectH = 60; // height of rectangle 
int rectW = 20; //  width of rectangle 
int n_rectangles = 5; // 5 rectangles to draw

size(800,800);

int size_x = margin * (n_rectangles-1); 
int size_y = margin * (n_rectangles-1); 

for (int i =  0; i < n_rectangles; ++i ) {
    for (int j =  0; j < n_rectangles; ++j ) {

         fill(255);

         pushMatrix();

         translate(width/2 - size_x/2 + i*margin, height/2 -size_y/2 + j*margin);
         rotate(radians(45));

         rect(-rectW/2, -rectH/2, rectW, rectH);

         popMatrix();
    }
}