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):
86 mean = sum(g[0] for g in groups) + (len(groups) - ngroups) * glue
87 if mean > self.width * ngroups:
90 for grouping in self.all_groupings(groups, ngroups, glue):
91 if max(g[0] for g in grouping) > self.width:
93 var = sum((g[0] - mean) ** 2 for g in grouping)
94 if best is None or best_var > var:
95 best, best_var = grouping, var
99 def all_groupings(self, groups, ngroups, glue):
102 yield [(groups[0][0], groups)]
104 next_groups = groups[1:]
105 for grouping in self.all_groupings(next_groups, ngroups, glue):
108 groups[0][0] + glue + grouping[0][0],
109 [groups[0]] + grouping[0][1]
113 for grouping in self.all_groupings(next_groups, ngroups - 1, glue):
115 (groups[0][0], [groups[0]])