【问题标题】:Convert .Net Color Objects to HEX codes and Back将 .Net 颜色对象转换为 HEX 代码并返回
【发布时间】:2010-11-02 04:39:11
【问题描述】:

根据问题标题,如何获取十六进制代码并将其转换为 .Net Color 对象,然后以另一种方式进行?

我用谷歌搜索并不断得到同样的方法,但这是行不通的。

 ColorTranslator.ToHtml(renderedChart.ForeColor)

返回颜色名称为“White”而不是“#ffffff”!以另一种方式执行似乎会产生奇怪的结果,只是在某些时候有效...

【问题讨论】:

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


    【解决方案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
    

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        【解决方案3】:

        类似:

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

        【讨论】:

        • 考虑到 OP 使用的方法已经完成了他们需要做的事情,这似乎有点过头了。
        • 不需要,我需要十六进制代码,无论是否是有效的 HTML 颜色。所以我需要白色的十六进制而不是“白色”。
        • 这就是为什么我没有发布完整的解析器,因为我不知道 OP 究竟需要什么......他似乎出于某种奇怪的原因拒绝使用颜色名称...... . 并且我所知道的没有 API 可以“像 HTML 一样进行颜色转换,但从未使用标准颜色名称”
        • 我需要使用 HEX 代码在 jQuery 插件中设置颜色。它使用十六进制来设置值。抱歉shoula提到它
        【解决方案4】:

        【讨论】:

        • ToArgb() 返回 int,而不是十六进制字符串。尝试将 int 转换为十六进制字符串会导致截断。例如,Green 会以"FF00" 而不是"00FF00" 结束。许多浏览器会将其解释为"FFFF0000" 的简写,从而导致红色。
        【解决方案5】:

        “白色”一种有效的 HTML 颜色。请看ColorTranslator.ToHtml:

        这个方法翻译一个颜色 结构为字符串表示 HTML 颜色的。这是常见的 颜色的使用名称,例如“红色”, “蓝色”或“绿色”,而不是字符串 数字颜色的表示 值,例如“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)));
            }
        }
        

        【讨论】:

        • 这是正确答案,应该有更多的票数。
        猜你喜欢
        • 1970-01-01
        • 2011-04-17
        • 2019-02-08
        • 1970-01-01
        • 2013-03-23
        • 2014-03-01
        • 1970-01-01
        • 1970-01-01
        • 2012-07-07
        相关资源
        最近更新 更多