简体   繁体   中英

Python pillow put text in center/middle

I am trying to put the text always in middle from very side. and i found this solution, but it doesnt work when i make the font size bigger.

I found this solution, it doesnt work too: Center-/middle-align text with PIL?

This is my snippets:

from PIL import Image, ImageFont, ImageDraw 
import textwrap


W, H = (2480,1754)
msg = "hello"
bg_color = "yellow"
font_name = 'Helvetica Neu Bold.ttf'
font_size = 500

im = Image.new("RGBA",(W,H), bg_color)
draw = ImageDraw.Draw(im)
myFont = ImageFont.truetype(font_name, font_size)

w, h = draw.textsize(msg)


# y_text=(H/2)-130

draw.text(((W-font_size)/2,(H-font_size)/2), msg, fill="black", font=myFont)

im.save("hello.png", "PNG")

The output is below: Click to see output

Can anyone help me how can i put it in middle?

I think, change:

w, h = draw.textsize(msg)

draw.text(((W-font_size)/2,(H-font_size)/2), msg, fill="black", font=myFont)

to:

w, h = draw.textsize(msg, font=myFont)

draw.text(((W-w)/2,(H-h)/2), msg, fill="black", font=myFont)

You are calculating the position from the font_size (500), but you need to be calculating from how big the message will be when written in myFont, at that font_size , and that is the (w, h) you get from asking draw.textsize() and giving it the font to work with.

Try option anchor='mm' to draw your text在此处输入图像描述

draw.text((W//2, H//2), msg, anchor='mm', fill="black", font=myFont)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM