Snippet $338 authored by Sébastien Adam

Python: générateur de dégradé (codes HTML)
#!/usr/bin/env python
# -*- coding: utf-8 -*-

class ColorGradient(object):
    """ based on this article:"""
    def __init__(self, start='#FFFFFF', stop='#000000', num_classes=4):
        self.__start = self._hex_to_RGB(start)
        self.__stop = self._hex_to_RGB(stop)
        self.__num_classes = num_classes
        self.__colors = [self.__start]

    def __get_start(self):
        return self._RGB_to_hex(self.__start)
    def __set_start(self, value):
        self.__start = self._hex_to_RGB(value)
        self.__colors = [self.__start]
    start = property(__get_start,__set_start)
    def __get_stop(self):
        return self._RGB_to_hex(self.__stop)
    def __set_stop(self, value):
        self.__stop = self._hex_to_RGB(value)
        self.__colors = [self.__start]
    stop = property(__get_stop,__set_stop)
    def __get_num_classes(self):
        return self.__num_classes
    def __set_num_classes(self, value):
        if value < 2:
            raise ValueError('You need at least 2 classes')
        self.__num_classes = value
        self.__colors = [self.__start]
    num_classes = property(__get_num_classes,__set_num_classes)
    def __get_colors(self):
        if len(self.__colors) != self.__num_classes:
            if self.__num_classes == 2:
        return [self._RGB_to_hex(RGB) for RGB in self.__colors]
    colors = property(__get_colors)

    def _hex_to_RGB(self, hex):
       """ "#FFFFFF" -> [255,255,255] """
       # Pass 16 to the integer function for change of base
       return [int(hex[i:i+2], base=16) for i in range(1,6,2)]

    def _RGB_to_hex(self, RGB):
       """ [255,255,255] -> "#FFFFFF" """
       # Components need to be integers for hex to make sense
       RGB = [int(x) for x in RGB]
       return "#"+"".join(["0{0:x}".format(v) if v < 16 else "{0:x}".format(v) for v in RGB])

    def _generate(self):
        for t in range(1, self.__num_classes):
            curr_vector = [int(self.__start[j] + (float(t)/(self.__num_classes-1))*(self.__stop[j]-self.__start[j])) for j in range(3)]