用C ++创建两种颜色的线性渐变.ppm文件

时间:2015-10-20 03:23:25

标签: c++ gradient ppm

对于学校作业,我需要使用C ++创建一个.ppm文件,该文件是从一种颜色到另一种颜色的渐变。我还必须定义.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;

}

1 个答案:

答案 0 :(得分:0)

所呈现的代码的主要问题是它使用整数算术。就这样,例如x / 255为每个小于255的x值产生0。此计算应以浮点(最好是类型double,这是默认值)完成,您可以通过编写{ {1}},然后将最终结果转换为整数。

这样,通过可靠的计算,您可以更轻松地发现其他问题。

希望。 ; - )