-
Notifications
You must be signed in to change notification settings - Fork 84
/
Copy pathtext.py
53 lines (40 loc) · 1.6 KB
/
text.py
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
from PIL import Image, ImageDraw, ImageFont
from papirus import Papirus
WHITE = 1
BLACK = 0
class PapirusText(object):
def __init__(self, rotation=0):
self.papirus = Papirus(rotation=rotation)
def write(self, text, size=20,
fontpath='/usr/share/fonts/truetype/freefont/FreeMono.ttf',
maxlines=100):
# initially set all white background
image = Image.new('1', self.papirus.size, WHITE)
# prepare for drawing
draw = ImageDraw.Draw(image)
font = ImageFont.truetype(fontpath, size)
# Calculate the max number of char to fit on line
lineSize = (self.papirus.width / (size*0.65))
currentLine = 0
# unicode by default
textLines = [u""]
# Compute each line
for word in text.split():
# Always add first word (even when it is too long)
if len(textLines[currentLine]) == 0:
textLines[currentLine] += word
elif (draw.textsize(textLines[currentLine] +
" " + word, font=font)[0]) < self.papirus.width:
textLines[currentLine] += " " + word
else:
# No space left on line so move to next one
textLines.append(u"")
if currentLine < maxlines:
currentLine += 1
textLines[currentLine] += word
currentLine = 0
for line in textLines:
draw.text((0, size*currentLine), line, font=font, fill=BLACK)
currentLine += 1
self.papirus.display(image)
self.papirus.update()