我需要为待办事项列表中的多个项目随机生成颜色。
(例如接孩子放学、取干洗等等)
在Ruby中,最好的方法是什么?同时也要避免使用难以识别的颜色(例如灰色、白色等等)。
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
在哪里
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
这个功能是从此处移植而来,相关解释可以在同一维基百科文章中找到。
要生成RGB格式的随机颜色,您只需要随机生成三个组件(例如rand(256)
三次)。
如果您不希望颜色太亮,有很多方法可以确保这一点。例如,允许每个组件仅在其正常范围的一半内(rand(128)
)。由于较大的数字代表更亮的颜色,因此您不会得到白色、米色或任何其他“难以看清”的颜色。
您还可以要求所有组件的总和足够小,或者发明一些其他指标。例如,在这里,您可以找到一些更准确的“亮度”公式。
但是,如果您只需要有限数量的颜色(例如10或16种),那么最好准备一个列表(蓝色、绿色、橙色、栗色、紫罗兰等),并从中选择颜色。