我在我的摘要文件夹中找到了这个旧的褪色功能,并希望将其实现到我的一个项目中。可用于将一种颜色淡化为另一种颜色。这是一个很长的一线:
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
只是一个DWORD
(unsigned long
)。颜色可以是0xAARRGGBB(A-alpha,R-红色,G-绿色,B-蓝色),但也可以与其他合成物一起使用。显然这是一团糟,但这正是我所需要的。
问题在于它无法按预期工作:
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
我实际上不知道它是如何工作的,也不记得我从哪里来的,所以我在这里寻求帮助。要么帮助我找到错误,要么找到可以实现此目的的替代函数。
最佳答案
您现在应该做的是,首先,您应该花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_;
}
关于c - 褪色功能错误,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16819253/