我的首选方法是在色轮上找到n 均匀分布的点。
我们将色轮表示为 0 到 360 之间的值范围。因此,我们将使用的值是 360 / n * 0、360 / n * 1、...、360 / n * (n - 1)。在此过程中,我们定义了每种颜色的 hue。通过将饱和度设置为 1,将亮度设置为 1,我们可以将这些颜色中的每一种描述为色相饱和度 (HSV) 颜色。
(饱和度越高,颜色越“丰富”;饱和度越低,颜色越接近灰色。亮度越高,颜色“越亮”;亮度越低,颜色越“深”。)
现在,我们通过简单的计算得出每种颜色的 RGB 值。
http://en.wikipedia.org/wiki/HSL_and_HSV#Conversion_from_HSV_to_RGB
请注意,给出的方程式可以简化:
-
p = v * (1 - s) = 1 * (1 - 1) = 1 * 0 = 0
-
q = v * (1 - f * s) = 1 * (1 - f * 1) = 1 - f
-
t = v * (1 - (1 - f) * s) = 1 * (1 - (1 - f) * 1) = 1 - (1 - f) = 1 - 1 + f = f
Python 中的伪代码实现
注意:这是一个非常低效的实现。用 Python 给出这个例子的目的本质上是为了让我可以给出可执行的伪代码。
import math
def uniquecolors(n):
"""Compute a list of distinct colors, each of which is represented as an RGB 3-tuple."""
hues = []
# i is in the range 0, 1, ..., n - 1
for i in range(n):
hues.append(360.0 / i)
hs = []
for hue in hues:
h = math.floor(hue / 60) % 6
hs.append(h)
fs = []
for hue in hues:
f = hue / 60 - math.floor(hue / 60)
fs.append(f)
rgbcolors = []
for h, f in zip(hs, fs):
v = 1
p = 0
q = 1 - f
t = f
if h == 0:
color = v, t, p
elif h == 1:
color = q, v, p
elif h == 2:
color = p, v, t
elif h == 3:
color = p, q, v
elif h == 4:
color = t, p, v
elif h == 5:
color = v, p, q
rgbcolors.append(color)
return rgbcolors
Python 中的简洁实现
import math
v = 1.0
s = 1.0
p = 0.0
def rgbcolor(h, f):
"""Convert a color specified by h-value and f-value to an RGB
three-tuple."""
# q = 1 - f
# t = f
if h == 0:
return v, f, p
elif h == 1:
return 1 - f, v, p
elif h == 2:
return p, v, f
elif h == 3:
return p, 1 - f, v
elif h == 4:
return f, p, v
elif h == 5:
return v, p, 1 - f
def uniquecolors(n):
"""Compute a list of distinct colors, ecah of which is
represented as an RGB three-tuple"""
hues = (360.0 / n * i for i in range(n))
hs = (math.floor(hue / 60) % 6 for hue in hues)
fs = (hue / 60 - math.floor(hue / 60) for hue in hues)
return [rgbcolor(h, f) for h, f in zip(hs, fs)]