14. June 2009 by Mads

In my current game (Balloon Mayhem) I needed to pick a random color from an predefined list of colors. The way I solved this were to make an string[] of the colors as hex values (ex. #FF000000 for black) and then just pick a random index into this array each time a need a new color. My problem were to convert the hex values, in string format, to a real .NET Color. I Googled it a little and found some articles about generating brushes this way. I just altered the code a little and got this one:

private Color GetColorFromHexa(string hexaColor)
        {
            return Color.FromArgb(
                    Convert.ToByte(hexaColor.Substring(1, 2), 16),
                    Convert.ToByte(hexaColor.Substring(3, 2), 16),
                    Convert.ToByte(hexaColor.Substring(5, 2), 16),
                    Convert.ToByte(hexaColor.Substring(7, 2), 16));
        }

Feel free to use it :)

- Enjoy!

Comments

Martin Hyldahl
Martin Hyldahl Denmark
29. Jun 2009 02:06
The .NET framework already has html hex color converter.
Take a look at System.Drawing.ColorConverter.FromHtml

-- Hyldahl
Mads
Mads
29. Jun 2009 10:41
I haven't checked it, but I don't think that's a part of Silverlight, which is why I created my own Smile
Comments are closed