接受的答案甚至没有真正回答这个问题......
C++
这是我的引擎中的一个简单的 C++ 代码段,它在三种任意颜色之间线性有效地插值:
const MATH::FLOAT4 color1(0.0f, 1.0f, 0.0f, 1.0f); // Green
const MATH::FLOAT4 color2(1.0f, 1.0f, 0.0f, 1.0f); // Yellow
const MATH::FLOAT4 color3(1.0f, 0.0f, 0.0f, 1.0f); // Red
MATH::FLOAT4 get_interpolated_color(float interpolation_factor)
{
const float factor_color1 = std::max(interpolation_factor - 0.5f, 0.0f);
const float factor_color2 = 0.5f - fabs(0.5f - interpolation_factor);
const float factor_color3 = std::max(0.5f - interpolation_factor, 0.0f);
MATH::FLOAT4 color;
color.x = (color1.x * factor_color1 +
color2.x * factor_color2 +
color3.x * factor_color3) * 2.0f;
color.y = (color1.y * factor_color1 +
color2.y * factor_color2 +
color3.y * factor_color3) * 2.0f;
color.z = (color1.z * factor_color1 +
color2.z * factor_color2 +
color3.z * factor_color3) * 2.0f;
color.w = 1.0f;
return(color);
}
interpolation_factor
假定在 范围内0.0 ... 1.0
。
假设颜色在范围内0.0 ... 1.0
(例如对于 OpenGL)。
C#
这是用 C# 编写的相同函数:
private readonly Color mColor1 = Color.FromArgb(255, 0, 255, 0);
private readonly Color mColor2 = Color.FromArgb(255, 255, 255, 0);
private readonly Color mColor3 = Color.FromArgb(255, 255, 0, 0);
private Color GetInterpolatedColor(double interpolationFactor)
{
double interpolationFactor1 = Math.Max(interpolationFactor - 0.5, 0.0);
double interpolationFactor2 = 0.5 - Math.Abs(0.5 - interpolationFactor);
double interpolationFactor3 = Math.Max(0.5 - interpolationFactor, 0.0);
return (Color.FromArgb(255,
(byte)((mColor1.R * interpolationFactor1 +
mColor2.R * interpolationFactor2 +
mColor3.R * interpolationFactor3) * 2.0),
(byte)((mColor1.G * interpolationFactor1 +
mColor2.G * interpolationFactor2 +
mColor3.G * interpolationFactor3) * 2.0),
(byte)((mColor1.B * interpolationFactor1 +
mColor2.B * interpolationFactor2 +
mColor3.B * interpolationFactor3) * 2.0)));
}
interpolationFactor
假定在 范围内0.0 ... 1.0
。
假设颜色在 范围内0 ... 255
。