2017-09-05 85 views
0

我有一個介於0和1之間的值,我試圖確定用於表示值大小的顏色值。值越高,應該是「藍色」越多,值越低,應該是越紅,中間是綠色。所以RGB中的浮點值1應該是(0,0,255),RGB中的值0應該是(255,0,0),中間是(0,255,0)。我試圖實現它,但在我的實現中,最高值是白色,最低值是黑色,這不是我想要實現的。在C++中可視化從紅色到藍色的RGB漸變

有誰知道如何實現這個?

我的嘗試是:

unsigned int rgb[] = {0,0,0}; 
//16581375 = 255^3 
unsigned long colorValue = floatBetweenZeroAndOne * 16581375; 
rgb[0] = colorValue %255; 
rgb[1] = (colorValue/255) % 255; 
rgb[2] = ((colorValue/255)/255) % 255; 

回答

0

嘗試這種情況:

unsigned int rgb[] = { 0,0,0 }; 
float floatBetweenZeroAndOne = 0.25f; 

if (floatBetweenZeroAndOne <= 0.5f) 
{ 
    floatBetweenZeroAndOne *= 2.0f; 
    rgb[0] = (unsigned int)(255 * (1.0f - floatBetweenZeroAndOne) + 0.5f); 
    rgb[1] = (unsigned int)(255 * (floatBetweenZeroAndOne) + 0.5f); 
} 
else 
{ 
    floatBetweenZeroAndOne = floatBetweenZeroAndOne * 2.0f - 1.0f; 
    rgb[1] = (unsigned int)(255 * (1.0f - floatBetweenZeroAndOne) + 0.5f); 
    rgb[2] = (unsigned int)(255 * (floatBetweenZeroAndOne) + 0.5f); 
} 

它將平滑內插R G B分量之間的float顏色值。

+0

這工作。謝謝! – ddominnik

0

所以基本上你是說如果你的float變量是0,rgb [0]應該是0,如果你的變量是1,它應該是255。你的float變量* 255應該爲紅色做訣竅。讓我們從現在開始調用你的浮點變量floatValue。

現在我們來做藍色。這基本上與紅色相反。我們希望floatValue爲0時bluecolor爲255,floatValue爲1時爲0。您可以像這樣使用它:rgb [2] = 255 - floatValue * 255。

綠色的是最棘手的,我猜。我們希望該值上升如果0 < floatValue < 0.5並降低0.5當< floatValue < 1.我認爲if語句可以做到這一點。

總的來說,我會這樣編碼。我沒有測試過它。

unsigned float floatValue = 0.236; // Completely random number between zero and one. 
unsigned int rgb[] = {0,0,0}; 
rgb[0] = floatValue * 255; 
rgb[2] = 255 - floatValue * 255; 
if (floatValue > 0 && <= 0.5) 
{ 
    rgb[1] = floatValue * 512 // Since I guess you want it to be maxed out at 128. 
} 
else if (floatValue > 0.5 && floatValue <= 1) 
{ 
    rgb[1] = 255 - (floatValue - 0.5)*512; 
} 
else 
{ 
    cout << "floatValue has a value smaller than 0 or bigger than 1!"; 
    return -1; 
} 
0

這樣的功能應該做的工作

void setColor(double value, int* rgb){ 
    if(value > 1 || value < 0) return; 
    if(value > 0.5){ 
     value -= 0.5; 
     rgb[0] = 0; 
     rgb[1] = (int)((1-2*value)*255); 
     rgb[2] = (int)(2*value*255); 
    } 
    if(value <= 0.5){ 
     rgb[0] = (int)((1-2*value)*255); 
     rgb[1] = (int)(2*value*255); 
     rgb[2] = 0; 
    } 
} 
0

您也可以嘗試這個版本:

void rgbscalar(float scalar) 
{ 
    float ratio = 2 * scalar; 
    int r = 255 * (ratio - 1); 
    if (r < 0) r = 0; 

    int b = 255 * (1 - ratio); 
    if (b < 0) b = 0; 

    int g = 255 - b - r; 
    if (g < 0) g = 0; 

    std::cout << r << " " << g << " " << b << " : " << scalar << std::endl; 
} 
相關問題