原理:HSL色盘

HSL的H是色相,色相按角度分布如下,我们只需要根据角度取HSLB然后转RGB即可
在这里插入图片描述

代码

使用了System.Drawing.Color

        /// <summary>
        /// 根据温度返回颜色
        /// </summary>
        /// <param name="temp">传入的温度的权重</param>
        /// <param name="maxTemp">最大温度</param>
        /// <param name="minTemp">最小温度</param>
        /// <returns></returns>
        private static Color GetFromTempToColor(double temp, double maxTemp, double minTemp)
        {
            double ratio = (temp - minTemp) / (maxTemp - minTemp);//根据温度的权重计算一个比例
            double hue = 270 - ratio * 270;//计算色
            var color = HSLToColor(hue, 1, 0.6);
            return color;
        }

        /// <summary>
        /// HSL转RGB
        /// </summary>
        /// <param name="hue">色向</param>
        /// <param name="saturation">饱和度</param>
        /// <param name="lightness">亮度</param>
        /// <returns></returns>
        private static Color HSLToColor(double hue, double saturation, double lightness)
        {
            // 转换 HSL 到 RGB
            double c = (1 - Math.Abs(2 * lightness - 1)) * saturation;
            double x = c * (1 - Math.Abs((hue / 60) % 2 - 1));
            double m = lightness - c / 2;

            double red = 0, green = 0, blue = 0;

            if (hue >= 0 && hue < 60)
            {
                red = c;
                green = x;
            }
            else if (hue >= 60 && hue < 120)
            {
                red = x;
                green = c;
            }
            else if (hue >= 120 && hue < 180)
            {
                green = c;
                blue = x;
            }
            else if (hue >= 180 && hue < 240)
            {
                green = x;
                blue = c;
            }
            else if (hue >= 240 && hue < 300)
            {
                red = x;
                blue = c;
            }
            else if (hue >= 300 && hue < 360)
            {
                red = c;
                blue = x;
            }

            // 转换 RGB 到 Color
            byte r = (byte)((red + m) * 255);
            byte g = (byte)((green + m) * 255);
            byte b = (byte)((blue + m) * 255);

            return Color.FromArgb(r, g, b);
        }