8 for word in text.split():
10 words[-1] += ' ' + word
13 conj = len(word.lstrip('(').lstrip('[')) == 1
18 def text_with_tracking(draw, tracking, pos, text, fill=None, font=None):
21 width = font.getsize(c)[0]
22 draw.text((x, y), c, fill=fill, font=font)
26 class DoesNotFit(Exception):
31 def __init__(self, width, height, texts,
32 font, lines, leading, tracking,
39 self.leading = leading
40 self.tracking = tracking
41 self.align_h = align_h
42 self.align_v = align_v
44 self.margin_top = self.font.getbbox('l')[1]
46 self.glue = self.get_length(' ')
49 (self.get_length(word), word)
50 for word in self.texts
53 self.grouping = self.find_grouping(groups, self.lines, self.glue)
54 if self.grouping is None:
57 def get_length(self, text):
58 return self.font.getlength(text) + self.tracking * len(text)
60 def as_pil_image(self, color):
61 img = PIL.Image.new('RGBA', (self.width, self.height + 2 * self.margin_top))
62 draw = PIL.ImageDraw.ImageDraw(img)
64 font_letter_height = self.font.getmetrics()[0] - self.margin_top
66 y = self.align_v * (self.height - ((self.lines - 1) * self.leading + font_letter_height))
67 for group in self.grouping:
68 x = (self.width - group[0] + self.tracking) * self.align_h
69 self.align_h * - group[0] / 2
72 draw, self.tracking, (x, y),
73 w, fill=color, font=self.font
80 def find_grouping(self, groups, ngroups, glue):
84 mean = sum(g[0] for g in groups) + (len(groups) - ngroups) * glue
85 if mean > self.width * ngroups:
88 for grouping in self.all_groupings(groups, ngroups, glue):
89 if max(g[0] for g in grouping) > self.width:
91 var = sum((g[0] - mean) ** 2 for g in grouping)
92 if best is None or best_var > var:
93 best, best_var = grouping, var
97 def all_groupings(self, groups, ngroups, glue):
100 yield [(groups[0][0], groups)]
102 next_groups = groups[1:]
103 for grouping in self.all_groupings(next_groups, ngroups, glue):
106 groups[0][0] + glue + grouping[0][0],
107 [groups[0]] + grouping[0][1]
111 for grouping in self.all_groupings(next_groups, ngroups - 1, glue):
113 (groups[0][0], [groups[0]])