C ++中的双色线性渐变.ppm文件

时间:2016-10-19 04:57:23

标签: c++ linear-gradients

我正在用C ++创建一个函数,它根据用户输入的颜色和尺寸创建一个双色渐变.ppm文件。我遇到的主要问题是颜色的循环似乎重新开始进入图像的方式,如此处所示。 enter image description here

它应该看起来像图像的左侧部分,但具有相同的尺寸。这是我用来获取图像的代码。

#include <iomanip>
#include <iostream>
#include <fstream>
#include <string>

using namespace std;

struct Color
{
    int red;
    int green;
    int blue;
};

void smoosh(int rows, int cols, Color leftColor, Color rightColor, string  filename);
int main()
{
    int y;
    int x;
    Color l;
    Color r;
    string f;
    cout << "Left Color: ";
    cin >> l.red >> l.green >> l.blue;
    cout << "\nRight Color: ";
    cin >> r.red >> r.green >> r.blue;
    cout << "\nHeight: ";
    cin >> y;
    cout << "\nWidth: ";
    cin >> x;
    cout << "\nFile Name: ";
    cin >> f;
    smoosh(y, x, l, r, f);


    return 0;
}
void smoosh(int rows, int cols, Color leftColor, Color rightColor, string   filename)
{
    int maxI = 256;
    ofstream fout;
    fout.open(filename);
    fout << "P3\n";
    fout << cols << " " << rows << "\n" << maxI - 1 << "\n";
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            fout << (leftColor.red + ((j / 255.0) * (rightColor.red - leftColor.red))) << " ";
            fout << (leftColor.green + ((j / 255.0) * (rightColor.green - leftColor.green))) << " ";
            fout << (leftColor.blue + ((j / 255.0) * (rightColor.blue - leftColor.blue)))<< " ";
        }
        fout << endl;
    }
    fout.close();
}

上面图像的用户输入值是 左侧颜色:255 0 0 正确颜色:255 255 0 身高:200 宽度:400,提前感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

我认为应该像

current.red = leftcolor.red;

in the loop:

    current.red += (rightcolor.red - leftcolor.red)/cols

    fout << current.red

    ...