ColorTranslator 類別 - 處理顏色轉換好幫手

摘要:ColorTranslator 類別 - 處理顏色轉換好幫手

從 HTML 色碼 轉成 Color 的蠢方法:

   1:  string strColor = "#F0F8FF";
   2:  MatchCollection mc = Regex.Matches(strColor, @"([0-9A-Fa-f]{2})");
   3:   
   4:  Color c = new Color();
   5:  if (mc.Count == 3)
   6:  {
   7:      int r = Convert.ToInt32(mc[0].Groups[0].Value, 16);
   8:      int g = Convert.ToInt32(mc[1].Groups[0].Value, 16);
   9:      int b = Convert.ToInt32(mc[2].Groups[0].Value, 16);
  10:      c = Color.FromArgb(r, g, b);
  11:  }

 

 

使用 ColorTranslator 所提供的靜態方法 FromHtml(),果然輕鬆愉快許多:

   1:  string strColor = "#F0F8FF"; 
   2:  Color c = ColorTranslator.FromHtml(strColor);

 

 

 


 

MSDN Library 提及的注意事項:ColorTranslatorToHtml() method translates a Color structure to a string representation of an HTML color. This is the commonly used name of a color, such as "Red", "Blue", or "Green", and not string representation of a numeric color value, such as "FF33AA".

如果是 Color 轉成色碼話,ColorTranslator 提供的靜態方法 ToHtml(),很可惜就不能派上用場了。

   1:  Color c = Color.AliceBlue;
   2:  string strColor = ColorTranslator.ToHtml(c);
   3:  // Output: AliceBlue

 

 

土法煉鋼法出現:

   1:  Color c = Color.AliceBlue;
   2:  string cRGB = string.Format("#{0:X2}{1:X2}{2:X2}", c.R, c.G, c.B);
   3:  // Output: #F0F8FF

 

 


參考: ColorTranslator Class