最近需要做一个功能,就是根据温度显示物体的颜色,类似中国天气网:
/// <summary>
/// 根据温度获取颜色
/// 算法如下:
/// 1.定义色阶变化范围fromColor, toColor
/// 2.获取因子:factor = T / (MaxT - MinT);
/// 3.计算新的RGB
/// R = fromColor.R * (1 - factor) + toColor.R * factor
/// G = fromColor.G * (1 - factor) + toColor.G * factor
/// B = fromColor.B * (1 - factor) * toColor.B * factor
/// 4.如果多个色阶,重复上面的运算
/// </summary>
public static class TemperatuerColor
{
private static Color Red = Color.FromRgb(255, 0, 0);
private static Color Yellow = Color.FromRgb(255, 0, 0);
private static Color Blue = Color.FromRgb(255, 0, 0);
public static SolidColorBrush GetColor(double temperature, double maxtemperature, double mintemperature)
{
double ratio = temperature / (maxtemperature - mintemperature);
Color result1 = Compute(Blue, Yellow, ratio);
Color result2 = Compute(Yellow, Red, ratio);
Color result = Compute(result1, result2, ratio);
return new SolidColorBrush(result);
}
private static Color Compute(Color fromColor, Color toColor, double ratio)
{
byte r = (byte)(fromColor.R * (1.0f - ratio) + toColor.R * ratio);
byte g = (byte)(fromColor.G * (1.0f - ratio) + toColor.G * ratio);
byte b = (byte)(fromColor.B * (1.0f - ratio) + toColor.B * ratio);
return Color.FromRgb(r, g, b);
}
}
/// 算法如下:
/// 1.定义色阶变化范围fromColor, toColor
/// 2.获取因子:factor = T / (MaxT - MinT);
/// 3.计算新的RGB
/// R = fromColor.R * (1 - factor) + toColor.R * factor
/// G = fromColor.G * (1 - factor) + toColor.G * factor
/// B = fromColor.B * (1 - factor) * toColor.B * factor
/// 4.如果多个色阶,重复上面的运算
/// </summary>
public static class TemperatuerColor
{
private static Color Red = Color.FromRgb(255, 0, 0);
private static Color Yellow = Color.FromRgb(255, 0, 0);
private static Color Blue = Color.FromRgb(255, 0, 0);
public static SolidColorBrush GetColor(double temperature, double maxtemperature, double mintemperature)
{
double ratio = temperature / (maxtemperature - mintemperature);
Color result1 = Compute(Blue, Yellow, ratio);
Color result2 = Compute(Yellow, Red, ratio);
Color result = Compute(result1, result2, ratio);
return new SolidColorBrush(result);
}
private static Color Compute(Color fromColor, Color toColor, double ratio)
{
byte r = (byte)(fromColor.R * (1.0f - ratio) + toColor.R * ratio);
byte g = (byte)(fromColor.G * (1.0f - ratio) + toColor.G * ratio);
byte b = (byte)(fromColor.B * (1.0f - ratio) + toColor.B * ratio);
return Color.FromRgb(r, g, b);
}
}
我这里的颜色是红色->黄色->蓝色的渐变。如果需要增加新的色阶,就需要增加新的颜色.
Color result1 = Compute(Blue, Yellow, ratio);
Color result2 = Compute(Yellow, Red, ratio);
Color result = Compute(result1, result2, ratio);