开发者

How to generate a set of random colors where no two colors are almost similar?

I currently use the following function to generate a random hexadecimal representation of a color.

function getRandomColor($max_r = 192, $max_g = 192, $max_b = 192) {
    if ($max_r > 192) { $max_r = 192; }
    if ($max_g > 192) { $max_g = 192; }
    if ($max_b > 192) { $max_b = 192; }
    if ($max_r < 0) { $max_r = 0; }
    if ($max_g < 0) { $max_g = 0; }
    if ($max_b < 0) { $max_b = 0; }

    return '#' . dechex(rand(0, 192)) . dechex(rand(0, 192)) . dechex(rand(0, 192));
}

Notice that I set the max value to be 192 instead of 255 for the sole reason that I am avoiding very light colors, for the purpose that I would be using the random color as foreground in a white background.

My question is how do I generate an indefinitely numbered set of colors where there are no colors that are almost the same. e开发者_运维问答.g.: #D964D9 & #FF3EFF ?


It might be better to use HSV coordinates. If you don't need white or black, you can set S and V to their maximum values, and generate H values that are not too close to each other (mod 360 degrees). Then convert to RGB.


There are several methods which spring to mind:

  1. Set up a array of n standard colors and interchange them randomly to produce the desired "random" colors.
  2. Fill an array of n colors; generate a random color and check if there is something "close" already in the array. If so, choose another random color.
  3. Select each color as a deterministic sequence, like a simple hash value, designed to not produce duplicate values. Grey code springs to mind.


Your algorithm could randomly generate RGB colors (as it's doing now) however you could for example verify that the two R's are sufficiently different before accepting the color choice. The algorithm could repeat that step (say up to 4...10...N times) for a given R, G and/or B.

while ( (R1 > $max_r/2) && (R2 > $max_r/2) ) {
// Both are in the upper half of range, get a new random value for R1.
}

Other possibilities:

  • Repeat for the lower half of range
  • Further sub-divide ranges (into 1/3's or 1/4's)
  • Repeat for G and B tones
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜