-
Notifications
You must be signed in to change notification settings - Fork 2
/
text_vert_align
executable file
·79 lines (76 loc) · 2.56 KB
/
text_vert_align
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
#!/usr/bin/python3
#+
# Test of calculations for vertically-aligning text: comparison of
# alignment based on overall font metrics, versus specific text metrics.
# For the derivation of the formulas used, see the IPython notebook
# “Beginning Text”
# <https://gitlab.com/ldo/qahirah_notebooks/blob/master/Beginning%20Text.ipynb>,
# <https://bitbucket.org/ldo17/qahirah_notebooks/src/master/Beginning%20Text.ipynb>.
#
# Copyright 2015 by Lawrence D'Oliveiro <ldo@geek-central.gen.nz>. This
# script is licensed CC0
# <https://creativecommons.org/publicdomain/zero/1.0/>; do with it
# what you will.
#-
import sys
import os
import qahirah as qah
from qahirah import \
CAIRO, \
Colour, \
Rect, \
Vector
box_dimensions = Vector(300, 100)
margins = Vector(20, 20)
texts = \
(
"gamey", # descenders only
"ballot", # ascenders only
"battery", # ascenders and descenders
"woman", # neither
"WXM", # full height
)
bg_colour = Colour.grey(1)
main_colour = Colour.grey(0)
dim_colour = Colour.grey(0.9)
pix = qah.ImageSurface.create \
(
format = CAIRO.FORMAT_RGB24,
dimensions = (box_dimensions + margins) * Vector(2, len(texts)) + margins
)
ctx = \
(qah.Context.create(pix)
.set_operator(CAIRO.OPERATOR_SOURCE)
.set_source_colour(bg_colour)
.paint()
.set_font_size(60)
)
font_extents = ctx.font_extents
font_mid_y = (font_extents.ascent - font_extents.descent) / 2
for i, text in enumerate(texts) :
topleft = (box_dimensions + margins) * Vector(0, i) + margins
ctx.set_source_colour(dim_colour)
ctx.move_to(topleft + Vector(0, box_dimensions.y / 2))
ctx.rel_line_to((box_dimensions.x, 0))
ctx.stroke()
ctx.set_source_colour(main_colour)
ctx.move_to(topleft + Vector(0, font_mid_y) + Vector(0, box_dimensions.y / 2))
ctx.show_text(text)
ctx.rectangle(Rect.from_dimensions(box_dimensions) + topleft)
ctx.stroke()
topleft = (box_dimensions + margins) * Vector(1, i) + margins
ctx.set_source_colour(dim_colour)
ctx.move_to(topleft + Vector(0, box_dimensions.y / 2))
ctx.rel_line_to((box_dimensions.x, 0))
ctx.stroke()
ctx.set_source_colour(main_colour)
text_extents = ctx.text_extents(text)
text_mid_y = (- 2 * text_extents.y_bearing - text_extents.height) / 2
ctx.move_to(topleft + Vector(0, text_mid_y) + Vector(0, box_dimensions.y / 2))
ctx.show_text(text)
ctx.rectangle(Rect.from_dimensions(box_dimensions) + topleft)
ctx.stroke()
#end for
pix \
.flush() \
.write_to_png("%s.png" % os.path.basename(sys.argv[0]))