How do I get the color from a hexadecimal color code using .NET?

前端 未结 16 774
不思量自难忘°
不思量自难忘° 2020-11-22 06:45

How can I get a color from a hexadecimal color code (e.g. #FFDFD991)?

I am reading a file and am getting a hexadecimal color code. I need to create the

相关标签:
16条回答
  • 2020-11-22 07:02

    I'm assuming that's an ARGB code... Are you referring to System.Drawing.Color or System.Windows.Media.Color? The latter is used in WPF for example. I haven't seen anyone mention it yet, so just in case you were looking for it:

    using System.Windows.Media;
    
    Color color = (Color)ColorConverter.ConvertFromString("#FFDFD991");
    
    0 讨论(0)
  • 2020-11-22 07:03

    If you mean HashCode as in .GetHashCode(), I'm afraid you can't go back. Hash functions are not bi-directional, you can go 'forward' only, not back.

    Follow Oded's suggestion if you need to get the color based on the hexadecimal value of the color.

    0 讨论(0)
  •     private Color FromHex(string hex)
        {
            if (hex.StartsWith("#"))
                hex = hex.Substring(1);
    
            if (hex.Length != 6) throw new Exception("Color not valid");
    
            return Color.FromArgb(
                int.Parse(hex.Substring(0, 2), System.Globalization.NumberStyles.HexNumber),
                int.Parse(hex.Substring(2, 2), System.Globalization.NumberStyles.HexNumber),
                int.Parse(hex.Substring(4, 2), System.Globalization.NumberStyles.HexNumber));
        }
    
    0 讨论(0)
  • 2020-11-22 07:11

    The three variants below give exactly the same color. The last one has the benefit of being highlighted in the Visual Studio 2010 IDE (maybe it's ReSharper that's doing it) with proper color.

    var cc1 = System.Drawing.ColorTranslator.FromHtml("#479DEE");
    
    var cc2 = System.Drawing.Color.FromArgb(0x479DEE);
    
    var cc3 = System.Drawing.Color.FromArgb(0x47, 0x9D, 0xEE);
    
    0 讨论(0)
  • 2020-11-22 07:11

    You could use the following code:

    Color color = System.Drawing.ColorTranslator.FromHtml("#FFDFD991");
    
    0 讨论(0)
  • 2020-11-22 07:13

    Use

    System.Drawing.Color.FromArgb(myHashCode);
    
    0 讨论(0)
提交回复
热议问题