1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
| # 生成色卡(彩虹渐变色) # 红 橙 黄 绿 青 蓝 紫 # r: 255, 255, 255, 0 , 0 , 0 , 139 # g: 0 , 165, 255, 255, 255, 0 , 0 # b: 0 , 0 , 0 , 0 , 255, 255, 255
def mid(left, right, cur, l_color, r_color): """ Get middle color """ if l_color < r_color: return int(l_color + (cur - left) * (r_color - l_color) / (right - left)) else: return int((right - cur) * (l_color - r_color) / (right - left))
def build_color(cnt, rgb_format='hex') -> list: """ Build uniform distribution color in rainbow colors card. """ hex_format = rgb_format == "hex" color = list() if cnt <= 0 or not isinstance(cnt, int): return color if cnt == 1: color.append((255, 0, 0)) return color color_step = (cnt - 1) / 6 for i in range(cnt): idx = int(i // color_step) if idx == 0: r, g, b = 255, mid(0, color_step, i, 0, 165), 0 elif idx == 1: r, g, b = 255, mid(color_step, color_step * 2, i, 165, 255), 0 elif idx == 2: r, g, b = mid(color_step * 2, color_step * 3, i, 255, 0), 255, 0 elif idx == 3: r, g, b = 0, 255, mid(color_step * 3, color_step * 4, i, 0, 255) elif idx == 4: r, g, b = 0, mid(color_step * 4, color_step * 5, i, 255, 0), 255 elif idx == 5: r, g, b = mid(color_step * 5, cnt, i, 0, 139), 0, 255 else: r, g, b = 139, 0, 255
if hex_format: # save as hexadecimal (以十六进制保存) color.append("#{:0^2}{:0^2}{:0^2}".format(*map((lambda x: x[2:]), map(hex, (r, g, b))))) else: # save as (r, g, b) tuple format (以元组的形式保存 r, g, b 值) color.append((r, g, b)) return color
if __name__ == '__main__': print(build_color(7))
|