PageRenderTime 7ms CodeModel.GetById 0ms RepoModel.GetById 0ms app.codeStats 0ms

/static/june_2007_style/gradient.py

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