How would I center-align (and middle-vertical-align) text when using PIL?
+2
A:
Use Draw.textsize
method to calculate text size and re-calculate position accordingly.
Here is an example:
from PIL import Image, ImageDraw
W, H = (300,200)
msg = "hello"
im = Image.new("RGBA",(W,H),"yellow")
draw = ImageDraw.Draw(im)
w, h = draw.textsize(msg)
draw.text(((W-w)/2,(H-h)/2), msg, fill="black")
im.save("hello.png", "PNG")
and the result:
jetxee
2009-12-28 18:49:48
+2
A:
Here is some example code which uses textwrap to split a long line into pieces, and then uses the textsize
method to compute the positions.
#!/usr/bin/env python
import Image
import ImageDraw
import ImageFont
import textwrap
astr='''The rain in Spain falls mainly on the plains.'''
para=textwrap.wrap(astr,width=15)
MAX_W,MAX_H=500,500
im = Image.new('RGB', (MAX_W, MAX_H), (0, 0, 0, 0))
draw = ImageDraw.Draw(im)
font = ImageFont.truetype('/usr/share/fonts/truetype/msttcorefonts/Arial.ttf', 36)
current_h=0
for line in para:
w,h=draw.textsize(line, font=font)
draw.text(((MAX_W-w)/2, current_h), line, font=font)
current_h+=h
im.save('test.png')
unutbu
2009-12-28 18:53:56