2013-05-29 39 views
0

我在我的代碼片段文件夾中發現了這種舊的色彩褪色功能,並希望將其實施到我的其中一個項目中。它可以用來淡化一種顏色到另一種顏色。這是一個很長的一行代碼:色彩褪色功能錯誤

D3DCOLOR GetFadedColor(D3DCOLOR from, D3DCOLOR to, float factor) 
{ 
    return (factor<0.0f)?from:((factor>1.0f)?to:((((from>>24)>(to>>24))?((from>>24)-(D3DCOLOR)(factor*(float)((from>>24)-(to>>24)))):((from>>24)+(D3DCOLOR)(factor*(float)((to>>24)-(from>>24))))<<24)|((((from<<8)>>24)>((to<<8)>>24))?(((from<<8)>>24)-(D3DCOLOR)(factor*(float)(((from<<8)>>24)-((to<<8)>>24)))):(((from<<8)>>24)+(D3DCOLOR)(factor*(float)(((to<<8)>>24)-((from<<8)>>24))))<<16)|((((from<<16)>>24)>((to<<16)>>24))?(((from<<16)>>24)-(D3DCOLOR)(factor*(float)(((from<<16)>>24)-((to<<16)>>24)))):(((from<<16)>>24)+(D3DCOLOR)(factor*(float)(((to<<16)>>24)-((from<<16)>>24))))<<8)|((((from<<24)>>24)>((to<<24)>>24))?(((from<<24)>>24)-(D3DCOLOR)(factor*(float)(((from<<24)>>24)-((to<<24)>>24)))):(((from<<24)>>24)+(D3DCOLOR)(factor*(float)(((to<<24)>>24)-((from<<24)>>24))))))); 
} 

D3DCOLOR只是一個DWORDunsigned long)。顏色可以是例如0xAARRGGBB(A-alpha,R-red,G-green,B-blue),但也可以與其他組合物一起使用。

顯然這是一團糟,但這正是我所需要的。

的問題是,因爲預期它不工作:

GetFadedColor(0x00000000, 0xff33cccc, 0.3f) 
// = 0x4c0f3d3d - working as intended 
GetFadedColor(0xff33cccc, 0x00000000, 0.3f) 
// = 0x000000bf - pretty wrong 
GetFadedColor(0xff00ff00, 0x00ff00ff, 0.3f) 
// = 0x004c00ff - second color value is correct, everything else wrong 

其實我不知道它是如何工作的,不記得在那裏我有它,所以我問這裏幫幫我。要麼幫我找到錯誤,要麼找到一個替代功能來做到這一點。

回答

1

你現在應該首先應該花5分鐘時間寫出一些真正基本的測試,並且知道你期望的情況。你甚至不需要使用任何測試框架,因爲拿到滾動你可以只使用assert

// basicTests.c 
#include <assert.h> 

int getFadedColor_basicTests() 
{ 
    assert(GetFadedColor(0x00000000, 0xff33cccc, 0.3f) == 0x4c0f3d3d && "30% from black to light blue should be greenish"); 
    assert(GetFadedColor(0xff33cccc, 0x00000000, 0.3f) == something && "30% from one color to another should be..."); 

    // if you're not sure what the exact value should be, you should write a helper function 
    // that returns true/false for if each of the four components of the actual color 
    // are in a sensible expected range 
    ... 
} 


int main() 
{ 
    getFadedColor_basicTests(); 
    return 0; 
} 

一旦你滿意的多少覆蓋率你測試得到的,是它只是3斷言總,或者如果你覺得它可能有50個斷言,你應該開始重新格式化一行,打破界限,添加有意義的縮進和評論。開始重構,提取出常用表達式,在他們做什麼或應該做什麼時添加註釋,所有這些都是在更改之間運行測試並在設計新測試時添加測試。

編輯:

是不是隻是應該線性外推單獨的每個組件?

int fade(int from_, int to_, float factor) 
{ 
    unsigned char *from = (unsigned char*)&from_; 
    unsigned char *to = (unsigned char*)&to_; 
    int result_; 
    unsigned char *result = (unsigned char*)&result_; 

    for (int i = 0 ; i < 4; ++i) 
    { 
     result[i] = factor * ((int)to[i] - (int)from[i]) + from[i]; 
    } 

    return result_; 
} 
+0

謝謝。我希望有人發現錯誤或有一個更清潔的解決方案。代碼似乎相當多餘,對於這項任務似乎有點多餘。 – typ1232

+0

@ typ1232對我的解決方案有幫助嗎? –

+0

非常感謝!這正是應該發生的事情。它是人類可讀的! – typ1232