PageRenderTime 29ms CodeModel.GetById 15ms app.highlight 11ms RepoModel.GetById 1ms app.codeStats 0ms

/static/june_2007_style/gradient.py

https://bitbucket.org/cistrome/cistrome-harvard/
Python | 74 lines | 57 code | 13 blank | 4 comment | 6 complexity | 8f33fd78ab6cc2a8aacb61b47d584710 MD5 | raw file
 1#!/usr/bin/env python
 2
 3"""
 4usage: %prog width height bg_color hatch_color [color alpha stop_pos] +
 5"""
 6
 7from __future__ import division
 8
 9import sys
10import cairo
11
12assert sys.version_info[:2] >= ( 2, 4 )
13
14def parse_css_color( color ):
15    if color.startswith( '#' ):
16        color = color[1:]
17    if len( color ) == 3:
18        r = int( color[0], 16 )
19        g = int( color[1], 16 )
20        b = int( color[2], 16 )
21    elif len( color ) == 6:
22        r = int( color[0:2], 16 )
23        g = int( color[2:4], 16 )
24        b = int( color[4:6], 16 )
25    else:
26        raise Exception( "Color should be 3 hex numbers" )
27    return r/256, g/256, b/256
28        
29def gradient( width, height, args ):
30    pat = cairo.LinearGradient(0.0, 0.0, 0.0, height)
31    while len( args ) > 2:
32        col = parse_css_color( args[0] )
33        alpha = float( args[1])
34        pos = float( args[2] )
35        pat.add_color_stop_rgba( pos, col[0], col[1], col[2], alpha )
36        args = args[3:]
37    return pat
38    
39def hatch( width, height, color ):
40    im_surf = cairo.ImageSurface( cairo.FORMAT_ARGB32, width, width )
41    c = cairo.Context( im_surf )
42    c.set_source_rgb ( *color )
43    c.set_line_width( 0.75 )
44    for i in range( 0, 2*max(height,width), 3 ):
45        c.move_to ( 0-10, i+10 )
46        c.line_to ( width+10, i - width - 10 )
47    c.stroke()
48    pat = cairo.SurfacePattern( im_surf )
49    pat.set_extend (cairo.EXTEND_REPEAT)
50    return pat
51                
52width = int( sys.argv[1] )
53height = int( sys.argv[2] )
54    
55surface = cairo.ImageSurface( cairo.FORMAT_ARGB32, width, height )
56c = cairo.Context( surface )
57
58c.rectangle(0,0,width,height)
59c.set_source_rgb( *parse_css_color( sys.argv[3] ) )
60c.fill()
61
62if sys.argv[4] != "-":
63    c.rectangle (0, 0, width, height)
64    c.set_source( hatch( width, height, parse_css_color( sys.argv[4] ) ) )
65    c.fill()
66
67pat = cairo.LinearGradient(0.0, 0.0, 0.0, height)
68pat.add_color_stop_rgba( 0, 1, 1, 1, 0 )
69pat.add_color_stop_rgba( 1, 1, 1, 1, 1 )
70c.rectangle (0, 0, width, height)
71c.set_source( gradient( width, height, sys.argv[5:] ) )
72c.fill()
73
74surface.write_to_png( "/dev/stdout" )