def makeColors(self): colors = { # use original RoboFab colors for Font and Glyph objects 'font': Color.from_hsl(80, 0.50, 0.49), 'glyph': Color.from_hsl(38, 0.91, 0.69), } # color set 1: Font sub-objects for i, obj in enumerate(self.colorSets[0][1:]): color = colors['font'].with_hue(colors['font'].hsl[0] + (i + 1) * 25) colors[obj] = color # color set 2: Glyph sub-objects for i, obj in enumerate(self.colorSets[1][1:]): color = colors['glyph'].with_hue(colors['glyph'].hsl[0] - (i + 1) * 15) colors[obj] = color # color set 3: Contour sub-objects for i, obj in enumerate(self.colorSets[2][1:]): color = colors['contour'].with_hue(colors['contour'].hsl[0] - (i + 1) * 20) colors[obj] = color # color set 4: Layer colors['layer'] = colors['font'].blend(colors['glyph'], percent=0.5) self.colors = colors
def to_color(*color_args) -> Color: """ Convert various color representations to grapefruit.Color Handles RGB triplets, hexcodes, and html color names. :return: The color """ colors = [] for arg in color_args: value = None if arg is not None: if isinstance(arg, Color): value = arg elif isinstance(arg, str): if arg != '': # grapefruit's default str() spews a string repr of a tuple strtuple = COLOR_TUPLE_STR.match(arg) if strtuple: value = Color.NewFromRgb(*[float(x) \ for x in strtuple.group(1).split(', ')]) else: value = Color.NewFromHtml(arg) elif isinstance(arg, Iterable): value = rgb_from_tuple(arg) else: raise TypeError('Unable to parse color from \'%s\' (%s)' % (arg, type(arg))) colors.append(value) if len(colors) == 0: return None if len(colors) == 1: return colors[0] return colors
def html_color(color): if color is None: return '#000000' if isinstance(color, Color): return color.html if isinstance(color, str): return Color.from_html(color).html return Color(color).html
def _refresh(self): try: self._refreshing = True # state value = self._get(LED.Command.GET_LED_STATE) if value is not None: self.state = bool(value[2]) # color value = self._get(LED.Command.GET_LED_COLOR) if value is not None: self.color = Color.NewFromRgb(value[2] / 255.0, value[3] / 255.0, value[4] / 255.0) # mode value = self._get(LED.Command.GET_LED_MODE) if value is not None: self.mode = LEDMode(value[2]) # brightness value = self._get_brightness() if value is not None: self.brightness = scale_brightness(int(value[2]), True) finally: self._refreshing = False
def gradient(length: int, *colors) -> list: """ Generate a looped gradient from multiple evenly-spaced colors Uses the new HSLUV colorspace :param length: Total number of entries in the final gradient :param colors: Color stops, varargs :return: List of colors in the gradient """ luv_colors = [rgb_to_hsluv(to_color(x).rgb) for x in colors] luv_colors.append(luv_colors[0]) steps = max(len(luv_colors), math.floor(length / (len(luv_colors)))) gradient = [] for color_idx in range(0, len(luv_colors) - 1): start = luv_colors[color_idx] end = luv_colors[(color_idx + 1)] for interp in range(0, steps): amount = float(interp) / float(steps) i = ColorUtils._circular_interp(start, end, amount) gradient.append( Color.NewFromRgb(*hsluv_to_rgb([i[0], i[1], i[2]]))) return gradient
def test_color_formats(): for color, output in [ ( (1.0, 0.0, 0.0), '#ff0000', ), ( Color.from_html('red'), '#ff0000', ), ( 'green', '#008000', ), ( '#123456', '#123456', ), ]: p = Pen() p.stroke_mode(2.0, color) p.move_to((0, 0)) p.turn_to(0) p.line_forward(5) assert_equal( p.paper.svg_elements(0)[0], '<path d="M0,-1 L0,1 L5,1 L5,-1 L0,-1 z" fill="{}" />'.format(output) )
def interference(length, freq1: float = 0.3, freq2: float = 0.3, freq3: float = 0.3, phase1: float = 0.0, phase2: float = 2.0, phase3: float = 4.0, center: float = 128.0, width: float = 127.0): """ Creates an interference pattern of three sine waves """ phase1 = phase1 * math.pi / 3 phase2 = phase2 * math.pi / 3 phase3 = phase3 * math.pi / 3 center /= 255.0 width /= 255.0 gradient = [] for i in range(0, length): r = math.sin(freq1 * i + phase1) * width + center g = math.sin(freq2 * i + phase2) * width + center b = math.sin(freq3 * i + phase3) * width + center gradient.append(Color.NewFromRgb(r, g, b)) return gradient
def rgb_from_tuple(arg: tuple) -> Color: """ Convert a 3-tuple of ints or floats to a Grapefruit color :param arg: The RGB tuple to convert :return: The Color object """ if len(arg) >= 3: if arg[0] is None: return Color.NewFromRgb(0, 0, 0) if all(isinstance(n, int) for n in arg): return Color.NewFromRgb(*Color.IntTupleToRgb(arg)) if all(isinstance(n, float) for n in arg): return Color.NewFromRgb(*arg) raise TypeError('Unable to convert %s (%s) to color' % (arg, type(arg[0])))
def inverse(color: ColorType) -> float: """ Get the RGB inverse of this color (1 - component) :param color: a color :return: Inverse of the given color """ rgb = color.rgb return Color.NewFromRgb(1.0 - rgb[0], 1.0 - rgb[1], 1.0 - rgb[2], color.alpha)
def hue_gradient(start: float=0.0, length: int=360) -> list: """ Generate a gradient which spans all hues :param start: starting hue :param length: number of colors which should be produced :return: list of colors """ step = 360 / length return [Color.NewFromHsv((start + (step * x)) % 360, 1, 1) for x in range(0, length)]
def increase_contrast(color: ColorType) -> Color: """ Performs contrast inversion if a hue rotation would result in white-on-white or black-on-black. :param color: The color to check :return: The new color with adjusted contrast """ hsl = list(color.hsl) if hsl[2] < 0.1 or hsl[2] > 0.7: hsl[2] = 1.0 - hsl[2] color = Color.NewFromHsl(*hsl, color.alpha) return color
def test_special_types(): obj, sig = dbus_prepare(Color.NewFromHtml('black')) assert obj == '#000000' assert sig == 's' obj, sig = dbus_prepare(Int(5)) assert isinstance(obj, dict) assert sig == 'a{sv}' for value in obj.values(): assert isinstance(value, GLib.Variant) obj, sig = dbus_prepare(EnumTest) assert isinstance(obj, tuple) assert sig == '(sss)'
def __init__(self, n, start=0, end=270): self.size = n h_all = linspace(start, end, n) v_all = [0.75, 0.80, 0.85, 0.9, 0.95, 1] s_all = [.8] self.c = {} hsv = [] rgb = [] for i in xrange(n): s = s_all[0] v = v_all[5 - mod(i, 3)] hsv.append([h_all[i] + 240, s, v]) rgb.append(Color.HsvToRgb(h_all[i], s, v)) self.c['rgb'] = array(rgb) self.c['hsv'] = array(hsv) self.iterator = {} self.iterator['rgb'] = self.it(n, self.c, 'rgb') self.iterator['hsv'] = self.it(n, self.c, 'hsv')
def random_generator(rgb: bool = False): """ Generate random colors using the golden ratio conjugate :param rgb: True if RGB tuples should be generated :return: generator: """ golden_ratio_conjugate = (1 + math.sqrt(5)) / 2 hue = random.random() c0 = Color.NewFromHsv(0, 1.0, 1.0) while True: hue += golden_ratio_conjugate hue %= 1 value = c0.ColorWithHue(hue * 360) if rgb: yield to_rgb(value) else: yield value
def hsv_gradient(color1: ColorType, color2: ColorType, steps: int) -> list: """ Generate a gradient between two points in HSV colorspace :param color1: Starting color :param color2: Ending color :param steps: Number of steps in the gradient :param loop: If the gradient should "loop" back around to it's starting point :return: List of colors in the gradient """ start = ColorUtils._hsva(color1) end = ColorUtils._hsva(color2) gradient = [] for x in range(0, steps): amount = float(x) / float(steps - 1) i = ColorUtils._circular_interp(start, end, amount) gradient.append(Color.NewFromRgb(*hsluv_to_rgb([i[0], i[1], i[2]]))) return gradient
def to_rgb(arg) -> tuple: """ Convert various representations to RGB tuples :return: An RGB int tuple """ if arg is None: return (0, 0, 0) if isinstance(arg, Color): return arg.intTuple[:3] if isinstance(arg, str): return Color.NewFromHtml(arg).intTuple[:3] if isinstance(arg, tuple) or isinstance(arg, list): if arg[0] is None: return (0, 0, 0) if isinstance(arg[0], list) or isinstance(arg[0], tuple) \ or isinstance(arg[0], str) or isinstance(arg[0], Color): return [to_rgb(item) for item in arg] return rgb_to_int_tuple(arg) raise TypeError('Unable to parse color from \'%s\' (%s)' % (arg, type(arg)))
from grapefruit import Color for k in Color.NAMED_COLOR: c = Color.NewFromHtml(Color.NAMED_COLOR[k], wref=Color.WHITE_REFERENCE['std_D50']) out = [k] out.append(c.html) r, g, b = c.rgb out.append([int(r * 255), int(g * 255), int(b * 255)]) out.append(list(c.hsv)) out.append(list(c.hsl)) l, a, b = c.lab out.append([l / 100.0, a, b]) #print 'colors.push( ' + str(out) +' );' print 'colors.' + k + ' = "' + c.html + '"'
def html2xterm256(color): r, g, b = Color.HtmlToRgb(html_color) r = int(r * 255) g = int(g * 255) b = int(b * 255) return rgb_to_xterm(r, g, b)
from PIL import Image, ImageDraw import sqlite3 from grapefruit import Color c1 = Color.NewFromHtml('#ffffff') c2 = Color.NewFromHtml('#660000') conn = sqlite3.connect('zon-tags-2.db') im = Image.new('RGBA', (20 * 52 + 60, (2012 - 1946) * 20 + 40)) sql = "SELECT substr(id, 0, 5) year, substr(id, 6, 2) issue, count(*) from articles group by year, issue order by year, issue" draw = ImageDraw.Draw(im) for y in range(1946, 2013): draw.text((5, 32 + (y - 1946) * 20), str(y), fill='black') for i in range(1, 53): draw.text((36 + (i) * 20, 10), str(i), fill='black') for res in conn.execute(sql): year, issue, count = map(int, res) y = 30 + (year - 1946) * 20 x = 30 + issue * 20 col = c2.Blend(c1, percent=count / 561.0) draw.rectangle((x, y, x + 19, y + 19), fill=col.html) im.save('heatmap-part.png', 'PNG')
def construct_color(loader, node): val = loader.construct_yaml_str(node) return Color.NewFromHtml(val)
class FontPartsColorScheme: colorSets = [ ['font', 'font lib', 'info', 'groups', 'kerning', 'features'], [ 'glyph', 'glyph lib', 'anchor', 'component', 'image', 'guideline', 'contour' ], ['contour', 'point', 'bPoint', 'segment'], ['font', 'layer', 'glyph'], ] baseColors = { # use the original RoboFab colors for Font and Glyph objects # calculate colors for all other objects from those two 'font': Color.from_hsl(80, 0.50, 0.49), 'glyph': Color.from_hsl(38, 0.91, 0.69), } def __init__(self): self.makeColors() def makeColors(self): ''' Calculate colors for all objects. Colors are stored in a dict as `grapefruit.Color` objects. ''' colors = self.baseColors.copy() # color set 1: Font sub-objects for i, obj in enumerate(self.colorSets[0][1:]): color = colors['font'].with_hue(colors['font'].hsl[0] + (i + 1) * 23) colors[obj] = color # color set 2: Glyph sub-objects for i, obj in enumerate(self.colorSets[1][1:]): color = colors['glyph'].with_hue(colors['glyph'].hsl[0] - (i + 1) * 15) colors[obj] = color # color set 3: Contour sub-objects for i, obj in enumerate(self.colorSets[2][1:]): color = colors['contour'].with_hue(colors['contour'].hsl[0] - (i + 1) * 20) colors[obj] = color # color set 4: Layer colors['layer'] = colors['font'].blend(colors['glyph'], percent=0.5) self.colors = colors @property def colorsRGB(self): colors = {} for obj, color in self.colors.items(): colors[obj] = color.rgb return colors @property def colorsCMYK(self): colors = {} for obj, color in self.colors.items(): colors[obj] = color.cmyk return colors def drawSwatches(self, pos, cellSize, padding, captions=False): x, y = pos w, h = cellSize save() translate(x, y) fontSize(w * .12) for colorSet in reversed(self.colorSets): save() for obj in colorSet: color = self.colorsRGB[obj] fill(*color) rect(0, 0, w, h) if captions: fill(0) text(obj, (w * .1, h * .2)) translate(w + padding, 0) restore() translate(0, (h + padding)) restore()
def __init__(self, first, second): self.first = Color.NewFromHtml(first) self.second = Color.NewFromHtml(second)
def __init__(self, hwid, caps): self._hardware_id = hwid self._rgb = caps.get('rgb', False) self._color = Color.NewFromHtml(caps.get('color', 'green')) self._has_modes = caps.get('has_modes', False)
def from_html(cls, html_string): rgb = GC.NewFromHtml(html_string).rgb return cls("rgb", *rgb)
def _hue_gradient(start, length): step = 360 / length return [ Color.NewFromHsv((start + (step * x)) % 360, 1, 1) for x in range(0, length) ]