Dot-Net

將 .Net 顏色對象轉換為 HEX 程式碼並返回

  • October 24, 2015

根據問題標題,如何獲取十六進制程式碼並將其轉換為 .Net Color 對象,然後以另一種方式進行?

我用Google搜尋並不斷得到同樣的方法,這是行不通的。

ColorTranslator.ToHtml(renderedChart.ForeColor)

它返回顏色的名稱,如“White”而不是“#ffffff”!以另一種方式做似乎有奇怪的結果,只在某些時候工作……

就像是 :

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

引用自:https://stackoverflow.com/questions/982028