demoshop

demo, trying to be the best_

之前demo介紹過偷機的轉換法,現在來說明一下正規的轉法,利用ColorTranslator類別可以快速的轉換

♥小提醒:首先我們要using System.Drawing 這個命名空間

▲ 之前我們轉#FF99CC讓它變ARGB的時候需要寫成這樣

string myColor = "#99ffcc";
MatchCollection hColor = Regex.Matches(myColor, @"([0-9A-Fa-f]{2})");
Color newColor = new Color();
if (hColor.Count == 3)
{
    int r = Convert.ToInt32(hColor[0].Groups[0].Value, 16);
    int g = Convert.ToInt32(hColor[1].Groups[0].Value, 16);
    int b = Convert.ToInt32(hColor[2].Groups[0].Value, 16);
    newColor = Color.FromArgb(r, g, b);
} 

▲現在我們有了ColorTranslator以後只需要這樣寫

string myColor = "#99ffcc";
 
string newColor;
 
Color c = ColorTranslator.FromHtml(myColor);
 
newColor = string.Format("A{0}、R{1}、G{2}、B{3}", c.A, c.R, c.G, c.B);
 
Response.Write(c);//輸出Color [A=255, R=153, G=255, B=204]  
 
Response.Write(newColor);//輸出 A255、R153、G255、B204 


▲能轉過去當然也可以轉回來

string newColor;
Color c = Color.Green;
string myColor = ColorTranslator.ToHtml(c);
newColor = string.Format("#{0:x2}{1:x2}{2:x2}", c.R, c.G, c.B);
Response.Write(newColor);//輸出#008000 

?小鋪廢言:早點找到這類別就好了,之前在轉的時候像瘋子一樣.........自己在組字串

回應討論