微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

我正在编写一个带有二维结构数组的 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 };
Color green = { 0,255,0 };
Color blue = { 0,255 };

//dimensions and color value for the 4 different shapes
drawRect(image,20,15,75,150,blue);
drawRect(image,100,50,red);
drawCircle(image,200,green);
drawCircle(image,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,而是将 red 的值按 green 指定的位数SHIFT,然后按 {{1 }}。

你想要这个:

blue

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。