首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何对这个方格进行居中?

如何对这个方格进行居中?
EN

Stack Overflow用户
提问于 2019-01-28 18:44:34
回答 1查看 186关注 0票数 1

我试图简单地生成一个由5个旋转矩形组成的网格。但网格不会以中心位置出现。有人能帮我吗?

代码语言:javascript
复制
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();

  }
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-01-28 19:10:56

我建议绘制单个“居中”矩形,矩形的起源是(-rectW/2, -rectH/2)

代码语言:javascript
复制
rect(-rectW/2, -rectH/2, rectW, rectH);

计算第一个矩形中心与最后一个矩形中心的距离,用于行和列:

代码语言:javascript
复制
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)

代码语言:javascript
复制
translate(width/2 - size_x/2 + i*margin, height/2 - size_y/2 + j*margin);

见最后代码:

代码语言:javascript
复制
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();
    }
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54408369

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档