我试图简单地生成一个由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();
}
}发布于 2019-01-28 19:10:56
我建议绘制单个“居中”矩形,矩形的起源是(-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();
}
}https://stackoverflow.com/questions/54408369
复制相似问题