Skip to content

Commit

Permalink
added support for multiline text drawing
Browse files Browse the repository at this point in the history
  • Loading branch information
allo- authored and radarhere committed Jun 18, 2015
1 parent a09da24 commit d626679
Showing 1 changed file with 42 additions and 0 deletions.
42 changes: 42 additions & 0 deletions PIL/ImageDraw.py
Original file line number Diff line number Diff line change
Expand Up @@ -257,6 +257,9 @@ def rectangle(self, xy, fill=None, outline=None):
# Draw text.

def text(self, xy, text, fill=None, font=None, anchor=None):
if "\n" in text:
return self.multiline_text(xy, text, fill, font, anchor)

ink, fill = self._getink(fill)
if font is None:
font = self.getfont()
Expand All @@ -273,10 +276,49 @@ def text(self, xy, text, fill=None, font=None, anchor=None):
mask = font.getmask(text)
self.draw.draw_bitmap(xy, mask, ink)

def multiline_text(self, xy, text, fill=None, font=None, anchor=None,
spacing=0, align="left"):
widths, heights = [], []
max_width = 0
lines = text.split("\n")
for line in lines:
line_width, line_height = self.textsize(line, font)
widths.append(line_width)
max_width = max(max_width, line_width)
heights.append(line_height)
left, top = xy
for idx, line in enumerate(lines):
if align == "left":
pass # left = x
elif align == "center":
left += (max_width - widths[idx]) / 2.0
elif align == "right":
left += (max_width - widths[idx])
else:
assert False, 'align must be either "left", "center" or "right"'
self.text((left, top),
line, fill, font, anchor)
top += heights[idx] + spacing
left = xy[0]

def multiline_textsize(self, text, font=None, spacing=0):
max_width = 0
height = 0
lines = text.split("\n")
for line in lines:
line_width, line_height = self.textsize(line, font)
height += line_height + spacing
max_width = max(max_width, line_width)
return max_width, height


##
# Get the size of a given string, in pixels.

def textsize(self, text, font=None):
if "\n" in text:
return multiline_textsize(text, font)

if font is None:
font = self.getfont()
return font.getsize(text)
Expand Down

0 comments on commit d626679

Please sign in to comment.