How would I center-align (and middle-vertical-align) text when using PIL?
Select the text that you want to center. in the Page Setup group, and then click the Layout tab. In the Vertical alignment box, click Center. In the Apply to box, click Selected text, and then click OK.
Python String center() MethodThe center() method will center align the string, using a specified character (space is default) as the fill character.
Right-click the text box for which you want to set vertical alignment. On the shortcut menu, click Format Text Box. In the Format Text Box dialog box, click the Text Box tab. In the Vertical alignment box, select Top, Middle, or Bottom.
To make text centred, select and highlight the text first, then hold down Ctrl (the control key) on the keyboard and press E.
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:
If your fontsize is different, include the font like this:
myFont = ImageFont.truetype("my-font.ttf", 16) draw.textsize(msg, font=myFont)
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.
from PIL import Image, ImageDraw, ImageFont import textwrap astr = '''The rain in Spain falls mainly on the plains.''' para = textwrap.wrap(astr, width=15) MAX_W, MAX_H = 200, 200 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', 18) current_h, pad = 50, 10 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 + pad im.save('test.png')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With