因為工作需要,必須運用客戶買的套件,針對客戶總裁與副總裁層級要看的報表,寫Web Excel,在設置樣式時,頗為苦惱,因為必須用System.Drawing.Color物件去指定顏色,偏偏網路上搜到的色見本的色碼都是16進位字串。
搜了一下,剛好搜到這個範例,記錄一下,以便日後便於翻查。
參考來源:http://silverlemma.blogspot.com/2009/03/c-converting-from-hex-string-to-color.html
節錄裡面的function,有了這個function,整個方便很多!
Color c = HexColor("#99ccff");public Color HexColor(String hex)
{
//remove the # at the front
hex = hex.Replace("#", "");
byte a = 255;
byte r = 255;
byte g = 255;
byte b = 255;
int start = 0;
//handle ARGB strings (8 characters long)
if (hex.Length == 8)
{
a = byte.Parse(hex.Substring(0, 2), System.Globalization.NumberStyles.HexNumber);
start = 2;
}
//convert RGB characters to bytes
r = byte.Parse(hex.Substring(start, 2), System.Globalization.NumberStyles.HexNumber);
g = byte.Parse(hex.Substring(start+2, 2), System.Globalization.NumberStyles.HexNumber);
b = byte.Parse(hex.Substring(start+4, 2), System.Globalization.NumberStyles.HexNumber);
return Color.FromArgb(a, r, g, b);
}
沒有留言:
張貼留言