How to convert Hex to RGB?

后端 未结 8 1762
暖寄归人
暖寄归人 2021-02-12 11:13

I am trying to use this to figure out if a color is light or dark

Evaluate whether a HEX value is dark or light

Now. It takes in a int



        
8条回答
  •  离开以前
    2021-02-12 12:05

    A little of topic, but here is an extension method to the Color struct I've created to calculate Luminance with different algorithms. Hope it helps you.

    public static class ColorExtensions
    {
        /// 
        /// Gets the luminance of the color. A value between 0 (black) and 1 (white)
        /// 
        /// The color.
        /// The type of luminance alg to use.
        /// A value between 0 (black) and 1 (white)
        public static double GetLuminance(this Color color, LuminanceAlgorithm algorithm = LuminanceAlgorithm.Photometric)
        {
            switch (algorithm)
            {
                case LuminanceAlgorithm.CCIR601:
                    return (0.2126 * color.R + 0.7152 * color.G + 0.0722 * color.B) / 255;
    
                case LuminanceAlgorithm.Perceived:
                    return (Math.Sqrt(0.241 * Math.Pow(color.R, 2) + 0.691 * Math.Pow(color.G, 2) + 0.068 * Math.Pow(color.B, 2)) / 255);
    
                case LuminanceAlgorithm.Photometric:
                    return (0.299 * color.R + 0.587 * color.G + 0.114 * color.B) / 255;
            }
    
        }
    
       /// 
       /// The luminances
       /// 
       public enum LuminanceAlgorithm
       {
           /// 
           /// Photometric/digital ITU-R
           /// 
           Photometric,
    
           /// 
           /// Digital CCIR601 (gives more weight to the R and B components, as preciev by the human eye)
           /// 
           CCIR601,
    
           /// 
           /// A perceived luminance
           /// 
           Perceived
       }
    }
    

提交回复
热议问题