Center-/middle-align text with PIL?

后端 未结 5 1010
长情又很酷
长情又很酷 2020-12-04 07:50

How would I center-align (and middle-vertical-align) text when using PIL?

5条回答
  •  萌比男神i
    2020-12-04 08:05

    One shall note that the Draw.textsize method is inaccurate. I was working with low pixels images, and after some testing, it turned out that textsize considers every character to be 6 pixel wide, whereas an I takes max. 2 pixels and a W takes min. 8 pixels (in my case). And so, depending on my text, it was or wasn't centered at all. Though, I guess "6" was an average, so if you're working with long texts and big images, it should still be ok.

    But now, if you want some real accuracy, you better use the getsize method of the font object you're going to use:

    arial = ImageFont.truetype("arial.ttf", 9)
    w,h = arial.getsize(msg)
    draw.text(((W-w)/2,(H-h)/2), msg, font=arial, fill="black")
    

    As used in Edilio's link.

提交回复
热议问题