将.Net Color Objects转换为HEX代码并返回

时间:2009-06-11 16:05:36

标签: .net colors hex system.drawing.color

根据问题标题,我如何获取十六进制代码并将其转换为.Net Color对象,并以其他方式执行此操作?

我用谷歌搜索并继续采用不起作用的相同方式。

 ColorTranslator.ToHtml(renderedChart.ForeColor)

返回颜色的名称,如'White'而不是'#ffffff'!从另一个方面来看似乎有奇怪的结果,只在某些时候工作......

5 个答案:

答案 0 :(得分:26)

类似的东西:

Color color = Color.Red;
string colorString = string.Format("#{0:X2}{1:X2}{2:X2}",
    color.R, color.G, color.B);

另一种方式做得有点复杂,因为#F00是一个有效的html颜色(意思是全红色)但是仍然可以使用正则表达式,这里是一个小样本类:

using System;
using System.Diagnostics;
using System.Drawing;
using System.Text.RegularExpressions;
using System.Collections.Generic;

public static class HtmlColors
{
    public static string ToHtmlHexadecimal(this Color color)
    {
        return string.Format("#{0:X2}{1:X2}{2:X2}", color.R, color.G, color.B);
    }

    static Regex htmlColorRegex = new Regex(
        @"^#((?'R'[0-9a-f]{2})(?'G'[0-9a-f]{2})(?'B'[0-9a-f]{2}))"
        + @"|((?'R'[0-9a-f])(?'G'[0-9a-f])(?'B'[0-9a-f]))$",
        RegexOptions.Compiled | RegexOptions.IgnoreCase);

    public static Color FromHtmlHexadecimal(string colorString)
    {
        if (colorString == null)
        {
            throw new ArgumentNullException("colorString");
        }

        var match = htmlColorRegex.Match(colorString);
        if (!match.Success)
        {
            var msg = "The string \"{0}\" doesn't represent"
            msg += "a valid HTML hexadecimal color";
            msg = string.Format(msg, colorString);

            throw new ArgumentException(msg,
                "colorString");
        }

        return Color.FromArgb(
            ColorComponentToValue(match.Groups["R"].Value),
            ColorComponentToValue(match.Groups["G"].Value),
            ColorComponentToValue(match.Groups["B"].Value));
    }

    static int ColorComponentToValue(string component)
    {
        Debug.Assert(component != null);
        Debug.Assert(component.Length > 0);
        Debug.Assert(component.Length <= 2);

        if (component.Length == 1)
        {
            component += component;
        }

        return int.Parse(component,
            System.Globalization.NumberStyles.HexNumber);
    }
}

用法:

// Display #FF0000
Console.WriteLine(Color.Red.ToHtmlHexadecimal());

// Display #00FF00
Console.WriteLine(HtmlColors.FromHtmlHexadecimal("#0F0").ToHtmlHexadecimal());

// Display #FAF0FE
Console.WriteLine(HtmlColors.FromHtmlHexadecimal("#FAF0FE").ToHtmlHexadecimal());

答案 1 :(得分:12)

“白色”有效的HTML颜色。请参阅ColorTranslator.ToHtml

  

此方法可转换颜色   结构到字符串表示   HTML颜色。这是常见的   使用了颜色的名称,例如“Red”,   “蓝色”或“绿色”,而不是字符串   表示数字颜色   值,例如“FF33AA”。

如果您的颜色无法映射到HTML颜色字符串,则此方法将返回颜色的有效十六进制。见这个例子:

using System;
using System.Drawing;

class Program
{
    static void Main()
    {
        Console.WriteLine(ColorTranslator.ToHtml(Color.White));
        Console.WriteLine(ColorTranslator.ToHtml(Color.FromArgb(32,67,89)));
    }
}

答案 2 :(得分:1)

如果要使用{ColorTranslator.FromHTML}将颜色转换回来,则“白色”是HTML颜色的有效字符串。但我发现这个实现需要在表示颜色的字符串之前的#符号,如果它不常见(例如,它适用于White和#FFFFFF,但它不适用于#White或FFFFFF)。 所以我尝试将转换放在try / catch块中,使转换为字符串添加'#',如果它抛出异常,那么我抓住它并在没有#的情况下进行转换。

答案 3 :(得分:1)

我编写了自己的.net扩展名,用于简单地从十六进制转换为整数,整数(ARGB)转换为颜色,反之亦然:

Imports System.Drawing
Imports System.Runtime.CompilerServices

Public Module ColorsExt

    Private Sub example_for_usage()
        Dim hex As String
        Dim c As Color = Color.Red
        hex = c.ToHexString() 'Converts color to hexadecimal string'
        c = hex.ToIntegerFromHex().ToColor() 'Gets Integer value from the hex string and simply convert it to Color()'
    End Sub

    <Extension> _
    Public Function ToColor(ByVal argb As Integer) As Color
        Return Color.FromArgb(argb)
    End Function

    <Extension> _
    Public Function ToIntegerFromHex(ByVal argb_hex_string As String) As Integer
        Return Int("&H" + argb_hex_string)
    End Function

    <Extension> _
    Public Function ToHexString(ByVal c As Color) As String
        Return String.Format("{0:X2}{1:X2}{2:X2}{3:X2}", c.A, c.R, c.G, c.B)
    End Function

    <Extension> _
    Public Sub FromHexString(ByVal c As Color, ByVal hex As String)
        c = hex.ToIntegerFromHex().ToColor()
    End Sub

    <Extension> _
    Public Function ToHexString(ByVal c As Integer) As String
        Return String.Format("{0:X8}", c)
    End Function

    <Extension> _
    Public Function ToArgb(ByVal c As Color) As Integer
        Return (c.A * &HFF0000) + (c.R * &HFF00) + (c.G * &HFF) + (c.B)
    End Function

End Module

答案 4 :(得分:-3)