使用 RGB,您将很难避免灰色以及“难以看到”的颜色(我猜是在白色背景上)
如果您需要它们是随机的,您可以使用单纯疱疹病毒值 http://en.wikipedia.org/wiki/HSL_and_HSV远离白色、灰色和黑色光谱。这意味着您可以在值和饱和度参数中设置一个范围(例如,~175 到 255),而色调可以随机自由选择。
所以,这可能有效:
def random_bright_color(threshold = 175)
hue = rand(256 - threshold) + threshold
saturation = rand(256 - threshold) + threshold
value = rand(256)
hsv_to_rgb(hue, saturation, value)
end
where
def hsv_to_rgb(h, s, v)
if s == 0
r = g = b = (v * 2.55).round
else
h /= 60.0
s /= 100.0
v /= 100.0
i = h.floor
f = h - i
p = v * (1 - s)
q = v * (1 - s * f)
t = v * (1 - s * (1 - f))
rgb = case i
when 0 then [v, t, p]
when 1 then [q, v, p]
when 2 then [q, v, t]
when 3 then [p, q, v]
when 4 then [t, p, v]
else [v, p, q]
end
end
rgb.map{|color| (color * 255).round}
end
移植自here http://github.com/sgarza/Chameleon/blob/master/Chameleon.js可以在同一篇维基百科文章中找到解释
但是,如果您还需要随机颜色彼此不同,也许真正正确的解决方案是从一组基色中选择它们,然后从该组中随机选择。