lena和shane,家庭日志,xulavigne,Lena&Shane

如何实现

C#: Drawing.Color 与 HTML Hex Color 相互转换

2015-12-25 xiirus.net Carlo Mendoza Shane Jhu

原文是这样的:


I was working on a small project that needed to colorize text from stored values and bitmap gradients which involved getting color values from individual pixels as RGB values or System.Drawing.Color values. The following code demonstrates how to convert back-and-forth between System.Drawing.Color and string values (#XXXXXX or the name). I’ve seen how some people have gone out of their way to do these conversions with their own code implementations, but why recreate what’s already in the .NET Framework?


I must admit though, I didn’t think this was already built-in until I searched MSDN.


就是说,对于 System.Drawing.Color 与 HTML中的HEX颜色(#XXXXXX 或颜色名称)的相互转换,许多人都是自己编写转换代码实现,但实际上,转换方法已经内置在 .NET Framework 中了。调用方式如下:


using System.Drawing;


//convert to the HTML color value of a 
//known System.Drawing.Color
string htmlNamedColorValue =
    ColorTranslator.ToHtml(Color.Crimson);
//output: "Crimson"
//convert to the HTML hex color value from 
//System.Drawing.Color with RGB values (208,0,0)
string htmlHexColorValueTwo =
    ColorTranslator.ToHtml(Color.FromArgb(0, 208, 0, 0));
//output: "#D00000"
//convert to System.Drawing.Color from HTML hex color value 
Color colorValueFrmHex =
    ColorTranslator.FromHtml("#FFFF33");
//output: System.Drawing.Color with RGB values (255,25,51)
//convert to System.Drawing.Color from HTML known color
Color colorValue =
    ColorTranslator.FromHtml("DarkRed");
//output: Color.DarkRed
string htmlHexColorValueThree =
    String.Format("#{0:X2}{1:X2}{2:X2}", colorValue.R,
                                         colorValue.G,
                                         colorValue.B);
//output: "#8B0000"


如果觉得文章还不错,请点个赞吧

8月 30 2020
太过信任,你或许会受骗,然而终日怀疑,你会饱受痛苦。

弗兰克•克莱恩 (Frank Crane 美国演员,导演)