home *** CD-ROM | disk | FTP | other *** search
/ PC Welt 2006 November (DVD) / PCWELT_11_2006.ISO / casper / filesystem.squashfs / usr / share / doc / python-cairo / examples / warpedtext.py < prev   
Encoding:
Python Source  |  2005-08-29  |  2.0 KB  |  86 lines

  1. #!/usr/bin/env python
  2.  
  3. import cairo
  4. import math
  5.  
  6. def warpPath(ctx, function):
  7.     first = True
  8.  
  9.     for type, points in ctx.copy_path():
  10.         if type == cairo.PATH_MOVE_TO:
  11.             if first:
  12.                 ctx.new_path()
  13.                 first = False
  14.             x, y = function(*points)
  15.             ctx.move_to(x, y)
  16.  
  17.         elif type == cairo.PATH_LINE_TO:
  18.             x, y = function(*points)
  19.             ctx.line_to(x, y)
  20.  
  21.         elif type == cairo.PATH_CURVE_TO:
  22.             x1, y1, x2, y2, x3, y3 = points
  23.             x1, y1 = function(x1, y1)
  24.             x2, y2 = function(x2, y2)
  25.             x3, y3 = function(x3, y3)
  26.             ctx.curve_to(x1, y1, x2, y2, x3, y3)
  27.  
  28.         elif type == cairo.PATH_CLOSE_PATH:
  29.             ctx.close_path()
  30.  
  31. def spiral(x, y):
  32.     theta0 = -math.pi * 3 / 4
  33.     theta = x / Width * math.pi * 2 + theta0
  34.     radius = y + 200 - x/7
  35.     xnew = radius*math.cos(theta)
  36.     ynew = radius*math.sin(-theta)
  37.     return xnew + Width/2, ynew + Height/2
  38.  
  39. def curl(x, y):
  40.     xn = x - Textwidth/2
  41.     #yn = y - Textheight/2
  42.     xnew = xn
  43.     ynew = y + xn ** 3 / ((Textwidth/2)**3) * 70
  44.     return xnew + Width/2, ynew + Height*2/5
  45.  
  46.  
  47. Width, Height = 512, 512
  48. surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, Width, Height)
  49. ctx = cairo.Context(surface)
  50. solidpattern = ctx.get_source()
  51.  
  52. # background
  53. pat = cairo.LinearGradient (0.0, 0.0, 0, Height)
  54. pat.add_color_stop_rgba (1, 0, 0, 0, 1)
  55. pat.add_color_stop_rgba (0, 1, 1, 1, 1)
  56.  
  57. ctx.rectangle (0,0,Width,Height)
  58. ctx.set_source (pat)
  59. ctx.fill ()
  60.  
  61. # foreground
  62. ctx.set_source (solidpattern)
  63. ctx.set_source_rgb (1,1,1)
  64.  
  65. ctx.select_font_face("Sans")
  66. ctx.set_font_size(80)
  67.  
  68. # spiral text
  69. ctx.new_path()
  70. ctx.move_to(0, 0)
  71. ctx.text_path("pycairo - " + "spam " * 5)
  72. warpPath(ctx, spiral)
  73. ctx.fill()
  74.  
  75. # curly text
  76. ctx.new_path()
  77. ctx.move_to(0, 0)
  78. ctx.set_source_rgb(0.3, 0.3, 0.3)
  79. text = "I am curly :)"
  80. ctx.text_path(text)
  81. Textwidth, Textheight = ctx.text_extents(text)[2:4]
  82. warpPath(ctx, curl)
  83. ctx.fill()
  84.  
  85. surface.write_to_png("warpedtext.png")
  86.