如何用C++单遍绘制向图像中心逐层缩小的交替矩形图案?
问题描述
需要用C++复现中心向外交替颜色的矩形环图案(从中心开始,每一圈矩形条纹交替使用两种颜色)。现有代码生成的图案不完整,要求必须单遍绘制,不能叠加或覆盖像素。
现有代码
void alternating_rectangles(fstream& image_out, int width, int height, int rectangle_width, color first_color, color second_color) { int center_x = width / 2; int center_y = height / 2; for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { int x_dist = abs(center_x - x); int y_dist = abs(center_y - y); bool is_first_color = (x_dist / rectangle_width) == (y_dist / rectangle_width) && (x_dist / rectangle_width) % 2 == 0; color pixel_color = is_start_color ? first_color : second_color; write_pixel(image_out, pixel_color); } } }
注:已具备write_pixel函数可将像素写入ppm文件,图像的打开/关闭由调用方处理;width/height为图像尺寸,rectangle_width为单条矩形条纹的厚度。
当前代码仅在对角线区域生成了正确颜色,其余区域未正确着色,图案不完整。
解决方法
原代码的核心错误在于判断逻辑:仅当x_dist和y_dist除以条纹厚度的结果相等时才应用first_color,这只覆盖了对角线附近的小范围区域。目标图案需要的是取x、y方向距离中心的最大条纹层数,再通过奇偶性判断颜色。
修正后的代码
void alternating_rectangles(fstream& image_out, int width, int height, int rectangle_width, color first_color, color second_color) { int center_x = width / 2; int center_y = height / 2; for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { int x_dist = abs(center_x - x); int y_dist = abs(center_y - y); // 计算x、y方向分别处于第几层矩形环 int x_level = x_dist / rectangle_width; int y_level = y_dist / rectangle_width; // 取最大层数作为当前像素所在的环层级 int max_level = max(x_level, y_level); // 根据层级奇偶性选择颜色 color pixel_color = (max_level % 2 == 0) ? first_color : second_color; write_pixel(image_out, pixel_color); } } }
逻辑说明
max_level代表当前像素所在的矩形环层数:中心区域(距离中心小于1个条纹宽度)为第0层,向外依次是第1层、第2层……- 通过判断层数的奇偶性,实现整层矩形环的交替着色,能覆盖整个图像区域,生成完整的交替矩形环图案。
内容的提问来源于stack exchange,提问作者Tony
相关产品推荐
相关产品推荐

