Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<h2>Enhanced version (includes all colour formats);</h2> <p>I needed one of these that also works with the 3 digit "Shorthand hexadecimal form" and the MS alpha channel versions (for <strong>Silverlight/WPF</strong>), so came up with this version to cover all <em>numeric</em> colour formats:</p> <pre><code>/// &lt;summary&gt; /// Convert a Hex color string to a Color object /// &lt;/summary&gt; /// &lt;param name="htmlColor"&gt;Color string in #rgb, #argb, #rrggbb or #aarrggbb format&lt;/param&gt; /// &lt;returns&gt;A color object&lt;/returns&gt; public static Color ColorFromString(string htmlColor) { htmlColor = htmlColor.Replace("#", ""); byte a = 0xff, r = 0, g = 0, b = 0; switch (htmlColor.Length) { case 3: r = byte.Parse(htmlColor.Substring(0, 1), System.Globalization.NumberStyles.HexNumber); g = byte.Parse(htmlColor.Substring(1, 1), System.Globalization.NumberStyles.HexNumber); b = byte.Parse(htmlColor.Substring(2, 1), System.Globalization.NumberStyles.HexNumber); break; case 4: a = byte.Parse(htmlColor.Substring(0, 1), System.Globalization.NumberStyles.HexNumber); r = byte.Parse(htmlColor.Substring(1, 1), System.Globalization.NumberStyles.HexNumber); g = byte.Parse(htmlColor.Substring(2, 1), System.Globalization.NumberStyles.HexNumber); b = byte.Parse(htmlColor.Substring(3, 1), System.Globalization.NumberStyles.HexNumber); break; case 6: r = byte.Parse(htmlColor.Substring(0, 2), System.Globalization.NumberStyles.HexNumber); g = byte.Parse(htmlColor.Substring(2, 2), System.Globalization.NumberStyles.HexNumber); b = byte.Parse(htmlColor.Substring(4, 2), System.Globalization.NumberStyles.HexNumber); break; case 8: a = byte.Parse(htmlColor.Substring(0, 2), System.Globalization.NumberStyles.HexNumber); r = byte.Parse(htmlColor.Substring(2, 2), System.Globalization.NumberStyles.HexNumber); g = byte.Parse(htmlColor.Substring(4, 2), System.Globalization.NumberStyles.HexNumber); b = byte.Parse(htmlColor.Substring(6, 2), System.Globalization.NumberStyles.HexNumber); break; } return Color.FromArgb(a, r, g, b); } </code></pre> <p>For a brush you use it like this:</p> <pre><code>return new SolidColorBrush(ColorFromString(colorString)); </code></pre> <p><em>Using byte.Parse is more efficient than Convert and requires no casting.</em></p> <p>Update: Fixed sub-string offsets for case 8. </p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload