我正在尝试混合两种编码为整数的颜色。这是我的小功能:
int blend (int a, int b, float ratio) {
if (ratio > 1f) {
ratio = 1f;
} else if (ratio < 0f) {
ratio = 0f;
}
float iRatio = 1.0f - ratio;
int aA = (a >> 24 & 0xff);
int aR = ((a & 0xff0000) >> 16);
int aG = ((a & 0xff00) >> 8);
int aB = (a & 0xff);
int bA = (b >> 24 & 0xff);
int bR = ((b & 0xff0000) >> 16);
int bG = ((b & 0xff00) >> 8);
int bB = (b & 0xff);
int A = ((int)(aA * iRatio) + (int)(bA * ratio));
int R = ((int)(aR * iRatio) + (int)(bR * ratio));
int G = ((int)(aG * iRatio) + (int)(bG * ratio));
int B = ((int)(aB * iRatio) + (int)(bB * ratio));
return A << 24 | R << 16 | G << 8 | B;
}
一切似乎都运行良好,但某些参数会产生错误的颜色。例如:
int a = 0xbbccdd;
int b = 0xbbccdd;
int c = blend(a, b, 0.5f); // gives 0xbaccdc, although it should be 0xbbccdd
我的猜测是,无论是乘以浮动比率还是强制转换都应该归咎于此,但我无法弄清楚它们有什么问题......
那么在java中混合两种颜色的正确方法是什么?