[2] | 1 | #!/usr/bin/env python |
---|
| 2 | |
---|
| 3 | """ |
---|
| 4 | usage: %prog width height bg_color hatch_color [color alpha stop_pos] + |
---|
| 5 | """ |
---|
| 6 | |
---|
| 7 | from __future__ import division |
---|
| 8 | |
---|
| 9 | import sys |
---|
| 10 | import cairo |
---|
| 11 | |
---|
| 12 | assert sys.version_info[:2] >= ( 2, 4 ) |
---|
| 13 | |
---|
| 14 | def 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 | |
---|
| 29 | def 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 | |
---|
| 39 | def 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 | |
---|
| 52 | width = int( sys.argv[1] ) |
---|
| 53 | height = int( sys.argv[2] ) |
---|
| 54 | |
---|
| 55 | surface = cairo.ImageSurface( cairo.FORMAT_ARGB32, width, height ) |
---|
| 56 | c = cairo.Context( surface ) |
---|
| 57 | |
---|
| 58 | c.rectangle(0,0,width,height) |
---|
| 59 | c.set_source_rgb( *parse_css_color( sys.argv[3] ) ) |
---|
| 60 | c.fill() |
---|
| 61 | |
---|
| 62 | if 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 | |
---|
| 67 | pat = cairo.LinearGradient(0.0, 0.0, 0.0, height) |
---|
| 68 | pat.add_color_stop_rgba( 0, 1, 1, 1, 0 ) |
---|
| 69 | pat.add_color_stop_rgba( 1, 1, 1, 1, 1 ) |
---|
| 70 | c.rectangle (0, 0, width, height) |
---|
| 71 | c.set_source( gradient( width, height, sys.argv[5:] ) ) |
---|
| 72 | c.fill() |
---|
| 73 | |
---|
| 74 | surface.write_to_png( "/dev/stdout" ) |
---|