【问题标题】:Creating two color linear gradient .ppm files in C++在 C++ 中创建两个颜色线性渐变 .ppm 文件
【发布时间】:2015-10-20 03:23:25
【问题描述】:

对于学校作业,我需要创建一个.ppm 文件,该文件是使用 C++ 从一种颜色到另一种颜色的渐变。我还必须定义.ppm 文件的列数和行数。我不知道如何在数学上创建渐变颜色。有人可以帮助数学和代码来实现这一目标吗?

到目前为止,我已经能够输出颜色,只是不知道如何使其渐变。

到目前为止,这是我的代码:

#include <iostream>
#include <fstream>

using namespace std;

struct Color{
    int r;
    int g;
    int b;
};

void Grad(int rows, int cols, Color c1, Color c2, string filename);

void Grad(int rows, int cols, Color c1, Color c2, string filename){
    ofstream out(filename + ".ppm");

    int y;
    int x;

    out << "P6\n"
        << cols << " " << rows << "\n"
        << "255\n";

    for (y = 0; y < rows; y++){

        for (x = 0; x < cols; x++) {

            unsigned char r,g,b;

            r = (c1.r + ((x / 255) * (c2.r - c1.r)));
            g = (c1.g + ((x / 255) * (c2.g - c1.g)));
            b = (c1.b + ((x / 255) * (c2.b - c1.b)));

            out << r << g << b;

        }

    }
}

int main(){
    string bw = "blackToWhite";
    string ry = "redToYellow";
    string fb = "fooToBar";

    Color black; black.r=0; black.g=0; black.b=0;
    Color white; white.r=255; white.g=255; white.b=255;
    Color red; red.r=255; red.g=0; red.b=0;
    Color yellow; yellow.r=255; yellow.g=255; yellow.b=0;
    Color foo; foo.r=21; foo.g=156; foo.b=221;
    Color bar; bar.r=253; bar.g=24; bar.b=129;

    Grad(64,256,black,white,bw);
    Grad(400,2000,red,yellow,ry);
    Grad(234,800,foo,bar,fb);

    return 0;

}

【问题讨论】:

    标签: c++ gradient ppm


    【解决方案1】:

    所呈现的代码的主要问题是它使用了整数运算。这样,例如对于小于 255 的每个 x 值,x / 255 产生 0。此计算应以浮点数进行(最好键入 double,这是默认值),您只需编写 x / 255.0,然后使用最终结果转换为整数。

    这样,通过可靠的计算,您将更容易发现其他问题。

    希望如此。 ;-)

    【讨论】:

    • 谢谢!这有点帮助。我想我可以弄清楚我遇到的其他问题哈哈
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-12-15
    • 2014-10-26
    • 2020-05-29
    • 1970-01-01
    • 2015-06-30
    • 2022-01-15
    • 1970-01-01
    相关资源
    最近更新 更多