2015-10-20 125 views
0

線性漸變.ppm格式文件,對於學校裏的功課,我需要建立一個.ppm文件,它是從一種顏色漸變到另一個使用C++。我還必須定義.ppm文件所具有的列數和行數。我不知道如何數學創建漸變顏色。有人可以幫助數學和代碼來實現這一目標嗎?創建兩種顏色在C++

到目前爲止,我已經能夠輸出的顏色,我只是不知道如何使它梯度。

這是到目前爲止我的代碼:

#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; 

} 

回答

0

的主要問題爲提供的代碼,是它使用整數運算。這樣,例如x/255產量0小於255該計算每x值應在浮點來完成(優選鍵入double,這是默認值),它可以通過編寫x/255.0簡單地做,然後用最終的結果轉換爲整數。

這樣一來,具有可靠的計算,你會更容易發現其他問題。

希望。 ;-)

+0

謝謝!這有所幫助。我想我可以弄清楚我遇到的其他問題,哈哈 –