+from StringIO import StringIO
+from librarian import get_resource, IOFile
+
+
+class TextBox(object):
+ """Creates an Image with a series of centered strings."""
+
+ SHADOW_X = 3
+ SHADOW_Y = 3
+ SHADOW_BLUR = 3
+
+ def __init__(self, max_width, max_height, padding_x=None, padding_y=None):
+ if padding_x is None:
+ padding_x = self.SHADOW_X + self.SHADOW_BLUR
+ if padding_y is None:
+ padding_y = self.SHADOW_Y + self.SHADOW_BLUR
+
+ self.max_width = max_width
+ self.max_text_width = max_width - 2 * padding_x
+ self.padding_y = padding_y
+ self.height = padding_y
+ self.img = Image.new('RGBA', (max_width, max_height))
+ self.draw = ImageDraw.Draw(self.img)
+ self.shadow_img = None
+ self.shadow_draw = None
+
+ def skip(self, height):
+ """Skips some vertical space."""
+ self.height += height
+
+ def text(self, text, color='#000', font=None, line_height=20,
+ shadow_color=None):
+ """Writes some centered text."""
+ text = re.sub(r'\s+', ' ', text)
+ if shadow_color:
+ if not self.shadow_img:
+ self.shadow_img = Image.new('RGBA', self.img.size)
+ self.shadow_draw = ImageDraw.Draw(self.shadow_img)
+ while text:
+ line = text
+ line_width = self.draw.textsize(line, font=font)[0]
+ while line_width > self.max_text_width:
+ parts = line.rsplit(' ', 1)
+ if len(parts) == 1:
+ line_width = self.max_text_width
+ break
+ line = parts[0]
+ line_width = self.draw.textsize(line, font=font)[0]
+ line = line.strip() + ' '
+
+ pos_x = (self.max_width - line_width) / 2
+
+ if shadow_color:
+ self.shadow_draw.text(
+ (pos_x + self.SHADOW_X, self.height + self.SHADOW_Y),
+ line, font=font, fill=shadow_color
+ )
+
+ self.draw.text((pos_x, self.height), line, font=font, fill=color)
+ self.height += line_height
+ # go to next line
+ text = text[len(line):]
+
+ def image(self):
+ """Creates the actual Image object."""
+ image = Image.new('RGBA', (self.max_width,
+ self.height + self.padding_y))
+ if self.shadow_img:
+ shadow = self.shadow_img.filter(ImageFilter.BLUR)
+ image.paste(shadow, (0, 0), shadow)
+ image.paste(self.img, (0, 0), self.img)
+ else:
+ image.paste(self.img, (0, 0))
+ return image