Debian Codegraph @

examples/cairo_snippets/snippets/warpedtext.py

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