I want to add an option to an API for the user to specify the colour of something. I would like it to accept reasonable representations of colours, probably including hex representations and also the various CSS colours. At first glance ColorTranslator.FromHtml()
appeared to be what I needed, but after a little experimentation I'm not so sure.
The MSDN documentation, read incautiously, would seem to suggest that ColorTranslator.FromHtml()
should support CSS colour specifications. However, it doesn't appear to support every syntax provided by CSS. For example, this will throw an exception:
// "rgb(255 is not a valid value for Int32"
Color c = ColorTranslator.FromHtml("rgb(255,255,255)");
Other colours are parsed differently to the rules for CSS found here. An 8-digit hex code is interpreted as AARRGGBB instead of RRGGBBAA:
Color c = ColorTranslator.FromHtml("#aabbccdd");
// 187, 204, 221, 170
Console.WriteLine($"{c.R}, {c.G}, {c.B}, {c.A}");
A 4-digit hex code is interpreted as RRGG (with the blue part being zero) rather than RGBA:
Color c = ColorTranslator.FromHtml("#abcd");
// 0, 171, 205, 0
Console.WriteLine($"{c.R}, {c.G}, {c.B}, {c.A}");
Why do these deviations exist and what exactly does the method support? Is it just that the method is old and frozen at an older version of CSS, but with some extensions tacked on that clash with more recent CSS standards?
I can't tell you why but I can tell you what is supported.
If you read the Source you can see how the colours are handled, essentially:
#771122
handled as #RRGGBB
#712
handled as #RGB
LightGrey
converted to LightGray
highlighttext
are converted to specific colours.Color.FromName
(I think)This is from a time before most of the things you were referring to even existed in the spec I think.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With