Repository navigation
Expand file tree
/
Copy pathrender.py
More file actions
62 lines (54 loc) · 2.35 KB
/
Copy pathrender.py
File metadata and controls
62 lines (54 loc) · 2.35 KB
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
"""Draws text with a TTF through FreeType (freetype-py), unhinted, for the
build checks, the chart and the specimens.
Pillow's own text drawing is not used: in Pillow 13 a glyph with two separate
contours above its body (the acute accent of À, É...) comes out one row too
high, although FreeType's bitmap is right.
"""
import freetype
from PIL import Image
EM_ABOVE = 1.1 # the frame's top, in ems above the baseline (the font's ascent)
EM_BELOW = 0.3 # the frame's bottom, in ems below it (its descent)
def _face(path, size):
face = freetype.Face(str(path))
face.set_pixel_sizes(0, size)
return face
def line(path, text, size, mono=True, pad=0):
"""Renders text on one line. Returns an 'L' image as tall as the font's
line (EM_ABOVE ems above the baseline, EM_BELOW below) and as wide as the text's
advances, plus pad pixels on each side. Glyphs sit at the nearest whole
pixel to their unhinted pen position."""
face = _face(path, size)
flags = freetype.FT_LOAD_RENDER | freetype.FT_LOAD_NO_HINTING
if mono:
flags |= freetype.FT_LOAD_TARGET_MONO
baseline = round(size * EM_ABOVE)
placed, pen = [], float(pad)
for ch in text:
face.load_char(ch, flags)
g = face.glyph
bm = g.bitmap
rows = []
for y in range(bm.rows):
row = bm.buffer[y * bm.pitch:(y + 1) * bm.pitch]
if mono:
rows.append([255 if row[x >> 3] >> (7 - (x & 7)) & 1 else 0 for x in range(bm.width)])
else:
rows.append(list(row[:bm.width]))
placed.append((int(pen + 0.5) + g.bitmap_left, baseline - g.bitmap_top, rows))
pen += g.linearHoriAdvance / 65536
width = max([int(pen + 0.5) + pad] + [x + len(r[0]) for x, _, r in placed if r])
im = Image.new("L", (max(width, 1), baseline + round(size * EM_BELOW)), 0)
px = im.load()
for x0, y0, rows in placed:
for dy, row in enumerate(rows):
for dx, v in enumerate(row):
if v and 0 <= x0 + dx < im.width and 0 <= y0 + dy < im.height:
px[x0 + dx, y0 + dy] = max(px[x0 + dx, y0 + dy], v)
return im
def advance(path, text, size):
face = _face(path, size)
pen = 0.0
for ch in text:
face.load_char(ch, freetype.FT_LOAD_NO_HINTING)
pen += face.glyph.linearHoriAdvance / 65536
return int(pen + 0.5)