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

我正在读取一个文件,并得到一个十六进制的颜色代码。我需要为十六进制颜色代码创建相应的System.Windows.Media.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)");

    }

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

其他回答

我猜这是ARGB代码…你指的是system。drawing。color还是system。windows。media。color ?例如,后者在WPF中使用。我还没见过有人提到它,所以以防你在找它:

using System.Windows.Media;

Color color = (Color)ColorConverter.ConvertFromString("#FFDFD991");
    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));
    }

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

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();

假设你是指HTML类型的RGB代码(称为十六进制代码,如#FFCC66),使用ColorTranslator类:

System.Drawing.Color col = System.Drawing.ColorTranslator.FromHtml("#FFCC66");

如果你使用的是ARGB十六进制代码,你可以使用System.Windows.Media命名空间中的ColorConverter类:

Color col = ColorConverter.ConvertFromString("#FFDFD991") as Color;
//or      = (Color) ColorConverter.ConvertFromString("#FFCC66") ;

你可以使用ColorConverter.ConvertFromString(string)方法将你的字符串(十六进制)转换为颜色。

示例:(这适用于ARGB,如“#FF1E1E1E”。

Control.Background = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#1E1E1E"));