Created
July 7, 2010 10:59
-
-
Save miracle2k/466559 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class ColorDict(object): | |
"""Provides a color for each key, trying to create as distinct a set | |
of colors as possible. | |
""" | |
# Minimum difference in hue between unique colors, before we begin | |
# to recycle old colors rather than generating new ones. | |
THRESHOLD = 0.05 | |
def __init__(self): | |
self._data = {} | |
self._index = 0 | |
# Pregenerate the colors. It would be nicer if this were done | |
# one demand, but since there is a rather limited set of color, | |
# it probably ain't not worth it. | |
self._colors = [] | |
divcount = 1 | |
while True: | |
step = 1.0 / (divcount*2) | |
if step < self.THRESHOLD: | |
break | |
for i in range(divcount): | |
color = (i*2*step+step, 0.5, 0.5) | |
self._colors.append(colorsys.hls_to_rgb(*color)) | |
divcount *= 2 | |
def _next_color(self): | |
if self._index >= len(self._colors): | |
self._index = 0 | |
self._index += 1 | |
return self._colors[self._index-1] | |
def __getitem__(self, key): | |
if not key in self._data: | |
self._data[key] = self._next_color() | |
return self._data[key] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment