如何初始化二维结构数组的值?

How do I initialize values of a 2d array of structs?

我正在编写一个 ppm 文件,其中包含充当 rgb 值的二维结构数组。该文件写入,但是当我尝试通过我的 drawRect 和 drawCircle 函数传递包含我想要的颜色值的结构时,图像没有按照我想要的尺寸绘制。像素值也没有正确写入数组。我有单独的函数来绘制矩形和圆形,createImg 绘制整个图像。

struct Color {
unsigned char red;
unsigned char green;
unsigned char blue;
};
int main() {

static Color image[LENGTH][WIDTH] = {};
createImg(image);
writeImg(image, 300, "torinCostales.ppm");

}

void createImg(Color image[][WIDTH]) {

//variables for red green and blue
Color red = { 255, 0, 0 };
Color green = { 0, 255, 0 };
Color blue = { 0, 0, 255 };

//dimensions and color value for the 4 different shapes
drawRect(image, 20, 15, 75, 150, blue);
drawRect(image, 100, 20, 100, 50, red);
drawCircle(image, 100, 200, 50, green);
drawCircle(image, 150, 150, 50, red);

//-------------------------------------------------------------------
//draws circle with given dimensions and sets array values to colorLevel
void drawCircle(Color image[][WIDTH],
int centerX, int centerY, int radius, Color colorLevel) {

for (int x = centerX - radius; x <= centerX + radius; x++)

   for (int y = centerY - radius; y <= centerY + radius; y++)
    
        if ((x - centerX) * (x - centerX) + (y - centerY) * (y - centerY) <= radius * radius)
        
            image[x][y] = colorLevel;
 }
        
//--------------------------------------------------------------------
//draws the rectangle with given dimensions and colorLevel
void drawRect(Color image[][WIDTH],
int rectTop, int rectLeft, int rectHeight, int rectWidth, Color colorLevel) {

for (int col = rectLeft; col < rectWidth + rectLeft; col++)

    for (int rows = rectTop; rows < rectHeight + rectTop; rows++)
    
        image[col][rows] = colorLevel;
}

//writes the file
void writeImg(const Color image[][WIDTH], int height, const string fileName) {

std::ofstream imgFile;
imgFile.open("torinCostales.ppm");

//header
imgFile << "P3";
imgFile << "\n" << WIDTH << ' ' << LENGTH;
imgFile << "\n" << "255" << "\n";

//writes pixel values
for (int row = 0; row < LENGTH; row++) {
    for (int col = 0; col < WIDTH; col++)
        imgFile << static_cast<int>(image[row][col].red << image[row][col].green << image[row][col].blue) << ' ';
    imgFile << '\n';
}

imgFile.close();

}
    

看起来这行是错误的:

imgFile << static_cast<int>(image[row][col].red << image[row][col].green << image[row][col].blue) << ' ';

不是将每种颜色转换为 int,而是 SHIFT red 的值green,然后 blue.

你想要这个:

imgFile << static_cast<int>(image[row][col].red)   << ' '
        << static_cast<int>(image[row][col].green) << ' '
        << static_cast<int>(image[row][col].blue)  << ' ';