john doe
john doe

Reputation: 23

How to center this grid of squares?

I am trying to simply produce a grid of 5 rotated rectangles. But the grid will not come out centered. Can anyone help me out?

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();

  }
}

Upvotes: 1

Views: 283

Answers (1)

Rabbid76
Rabbid76

Reputation: 211278

I recommend to draw single "centered" rectangles, the origin of the rectangle is (-rectW/2, -rectH/2):

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

Calculate the distance of the first rectangle center tor the last rectangle center, for row and column:

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

Translate to the center of the screen (width/2, height/2),
to the position of the upper left rectangle (-size_x/2, -size_y/2)
and finally each rectangle to its position (i*margin, j*margin):

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

See the final code:

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

Upvotes: 1

Related Questions