根據溫度擷取顏色

來源:互聯網
上載者:User

最近需要做一個功能,就是根據溫度顯示物體的顏色,類似中國天氣網:

 

 

 /// <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);
        }

    }

 

 我這裡的顏色是紅色->黃色->藍色的漸層。如果需要增加新的色階,就需要增加新的顏色.

Color result1 = Compute(Blue, Yellow, ratio);            

Color result2 = Compute(Yellow, Red, ratio);
Color result =  Compute(result1, result2, ratio);

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.