如何从十六进制颜色代码(例如#FFDFD991)中获得颜色?

我正在读取一个文件,并得到一个十六进制的颜色代码。我需要为十六进制颜色代码创建相应的System.Windows.Media.Color实例。框架中是否有一个内置的方法来做到这一点?


当前回答

你可以看到Silverlight/WPF用十六进制的颜色设置椭圆来使用十六进制值:

your_contorl.Color = DirectCast(ColorConverter.ConvertFromString("#D8E0A627"), Color)

其他回答

这篇文章已经成为任何试图从十六进制颜色代码转换为系统颜色的人的首选。因此,我认为我应该添加一个全面的解决方案,处理6位(RGB)和8位(ARGB)十六进制值。

默认情况下,根据微软,当从RGB转换为ARGB值

alpha值隐式为255(完全不透明)。

这意味着通过将FF添加到6位(RGB)十六进制颜色代码中,它就变成了8位ARGB十六进制颜色代码。因此,可以创建一个简单的方法来处理ARGB和RGB十六进制,并将它们转换为适当的颜色结构。

    public static System.Drawing.Color GetColorFromHexValue(string hex)
    {
        string cleanHex = hex.Replace("0x", "").TrimStart('#');

        if (cleanHex.Length == 6)
        {
            //Affix fully opaque alpha hex value of FF (225)
            cleanHex = "FF" + cleanHex;
        }

        int argb;

        if (Int32.TryParse(cleanHex, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out argb))
        {
            return System.Drawing.Color.FromArgb(argb);
        }

        //If method hasn't returned a color yet, then there's a problem
        throw new ArgumentException("Invalid Hex value. Hex must be either an ARGB (8 digits) or RGB (6 digits)");

    }

这是受到汉斯·凯斯汀的回答的启发。

还有一个简洁的扩展方法:

static class ExtensionMethods
{
    public static Color ToColor(this uint argb)
    {
        return Color.FromArgb((byte)((argb & -16777216)>> 0x18),      
                              (byte)((argb & 0xff0000)>> 0x10),   
                              (byte)((argb & 0xff00) >> 8),
                              (byte)(argb & 0xff));
    }
}

在使用:

Color color = 0xFFDFD991.ToColor();
    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));
    }

Use

System.Drawing.Color.FromArgb(myHashCode);

你可以看到Silverlight/WPF用十六进制的颜色设置椭圆来使用十六进制值:

your_contorl.Color = DirectCast(ColorConverter.ConvertFromString("#D8E0A627"), Color)