Entry 955

test

   

Submitted by Will on Aug. 25, 2008 at 11:34 a.m.
Language: Python. Code size: 2.1 KB.

#!/usr/bin/env python

from color import ColorRGBA
import itertools
from math import *


class ColourSequence(object):

    def __init__(self):

        self.colors = []
        self.type = "blend"


    def add(self, r, g, b):
        self.colors.append(ColorRGBA(r, g, b))

    def render(self, count):

        sequence = []

        colors = self.colors

        if self.type == "repeat":

            icolors = itertools.cycle(colors)
            for _ in range(count):
                sequence.append(icolors.next())

        elif self.type == "blend":

            num_colors = len(self.colors)

            for c in xrange(count):

                i = float(c) / (count-1)

                c1 = int(floor(i * (num_colors-1)))
                c2 = c1 + 1
                c1 = min(c1, num_colors-1)
                c2 = min(c2, num_colors-1)

                col1 = colors[c1]
                col2 = colors[c2]

                interpolant = i*(num_colors-1) - (floor(i*(num_colors-1)))
                inverse_interpolant = 1.0 - interpolant

                blend_col = ( col1 * inverse_interpolant ) + col2 * interpolant

                sequence.append(blend_col)

        return sequence

    def render_html(self, width=600, count=100):

        colors = self.render(count)

        col_width = width / count

        html = []

        html.append('<table border="0" cellpadding="0" cellspacing="0"><tr>')

        tdata = dict(width = col_width, height = 80)

        col_template = '<td width="%(width)i" height="%(height)i" bgcolor="%(col)s"></td>'

        for col in colors:
            tdata['col'] = col.as_html()
            html.append(col_template % tdata)

        html.append("</tr></table>")

        return "\n".join(html)

if __name__ == "__main__":

    c = ColourSequence()
    c.add(1.0,1.0,1.0)
    c.add(1,.2,0)
    c.add(.1, .8, 0)
    c.add(0., .9, 1.0)
    c.add(.8, .9, 0.1)
    c.add(.0, .0, 0.1)

    c.type="repeat"
    print c.render_html()
    c.type="blend"
    print c.render_html()

This snippet took 0.02 seconds to highlight.

Back to the Entry List or Home.

Delete this entry (admin only).