Question

I want to randomize a color, but with the somewhat obscure condition: Color mustn't be a shade of grey (hence, close to black/white).

What would be a neat way to do that?

My thought:
picking a basic palette of colors and then pick one randomly, and "playing" with it's RGB parameters.

Was it helpful?

Solution

Colors can be represented in ways other than a mix of red, green and blue. One model that will work better for this is a method called HSV (there is a similar model called HSL) meaning Hue, Saturation and Value. The Hue is the frequency of the color (rotation position on a color wheel) while saturation and value control how vibrant and how dark/light the color appears. Decide on a range for S and V then pick a random Hue and you should be good.

OTHER TIPS

Pseudo-code:

Generate value1 in range 0 to 255.

Generate value2 in range 0 to (value1 - 100) and (value1 + 100) to 255

Generate value3 in range 0 to min(value1,value2) - 100 and min(value1,value2) + 100 to 255.

Randomly assign value1,value2 and value3 to R G and B.

Generate random values for red (r), green (g) and blue (b). Then calculate

(r - g) * (r - g) + (r - b) * (r - b) + (g - b) * (g - b)

This quantity will give you a measure for how far away from grey the colour is. Zero would mean it's grey or black or white. A large number would mean it's saturated.

So, if this number turns out to be less than a certain threshold (maybe 5000 or so) then regenerate the numbers. You may have to play around a little to find the best threshold value for your needs.

The simplest way to structure this is probably with a do-while loop.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top