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);
    //output  

 

 

 

 

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

转载于:https://www.cnblogs.com/linpengfeixgu/archive/2008/08/13/1266831.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值