Alex Rivera | Logout

How do I create a random hex string that represents a color?

Asked 2009-04-08T15:50:38.843
51

I'm generating some charts that need a hex string for the colors.

Example:

<dataseries name="ford" color="FF00FF" />

I'm creating these dynamically, so I would like to generate the hex code for each dataseries randomly.

What is the best way to do this?

Edit
Report

1 Answer

14

A good way of generating a nice set of colours is to define them using fixed saturation and brightness and vary the hue.

  1. Set saturation and brightness to something you like, say 50% saturation and 90% brightness.
  2. Now divide the 360 degrees of hue by the number of distinct colours you want.
  3. Pick colours from HSV using that interval for hue, and the fixed S and V.

This gives you a nice set of colours, which all look like they came from the same 'set' -- all pastel, or all intense, or all off-white, whatever. And it's pretty easy to code if you've got Color.FromHSV().

It probably stops working once you get too many colours though, they'll be indistinguishable. But you'll probably get that problem anyway.

In pseudo code:

Sat = 0.5 * 255 //assuming we want range 0-255...
Brightness = 0.9 * 255
NumberOfColours = 7
HueSeparation = 360 / 7
Colors = []
for (i = 0 ; i< NumberOfColours; i++)
     Colors.Add(Color.FromHSV(HueSeparation * i, Sat, Brightness)

or

n = 7
Colors = [Color.FromHSV(x*360/n, 128, 230) for x in range(n)]

(I do like list comprehensions...)

answered 2009-04-08T16:57:00.683

Your Answer