Saturday, January 10, 2009

Generating many different colors with HSB color values

Update: A color picker w/Degrafa's built in palettes here

Someone on Flex Coders asked how to generate a series of random colors, and at the same time omit certain shades. I recently had a similar requirement. I used HSB color values to generate the distinct colors, and then converted them to the RGB values that we know and love.

Working w/HSB is more intuitive than RGB

Take a look at the ColorJack color sphere. Hue is an angle from 0 to 360, representing a color. At angle 0, the color is red. This just seems more intuitive than knowing how to combine varying amounts of red, green, and blue.

"Saturation" and "Balance" (or somtimes Brightness?) are also very intuitive. As saturation goes to zero, the color becomes more light. As balance goes to zero, the color becomes more dark. My description is not very scientific, but that's also my point.

My ColorManager class

I needed to generate a large number of fairly distinct colors. My approach was to rotate around the 360 degrees of hues, and vary saturation and brightness. I used this code to convert the HSB color to RGB.

Once you generate the colors, you can retrieve them as an array. Or, you can associate a color with a key name and retrieve it as needed.

// generate 100 colors
var cm:ColorManager = new ColorManager(100);

// configure optional properties
cm.initialHue = 180;  // start at hue angle of 180

// generate colors
cm.generateColors();

// retrieve as array
var a:Array = cm.colors;

// assign/retrieve a key's color just by asking for it
trace( _cm.getColorFor("foo") );
    
// now the key 'foo' is assigned a color
// if you want it later, ask for it
// with cm.getColorFor("foo")

Below is an example app that uses Degrafa to draw a bunch of squares. You can also try it here with more room to play with.

4 comments:

  1. looks great!
    You might also want to check out com.degrafa.paint.palette.PaletteUtils and
    com.degrafa.core.utils.ColorUtil
    you will see a bunch of helpful stuff there as well for color conversions and palette related support.

    ReplyDelete
  2. Can you post your original ColorManager class? The degrafa package doesn't work with Flex4, and it seems like your ColorManager class would be a great alternative.

    ReplyDelete
  3. Hi, if right click on the example in this post you can view/download the source for my ColorManager class. Looking back at it now, I think I'd do it differently :)

    I used Degrafa in this example, but not for generating the colors.

    Sunil

    ReplyDelete
  4. Sweet! I just noticed a new class in Flex 4 named HSBColor that has methods to convert HSB to RGB and vice versa!

    Using this class should make generating colors with the HSB color space trivial!

    ReplyDelete