Cannot align text with PIL text correctly

I use PIL to draw text on an image.

I did, as in this example, the center / middle alignment text with PIL? but it worked, however, when the text phrase changes lines, they are not aligned.

The font is Verdana. Where could the problem be?

Displays 5 pixels correctly on the right side.

colour = 'white' text = 'Attack Speed 3.7' font = ImageFont.truetype("static/fonts/verdana.ttf", 10) draw = ImageDraw.Draw(base) w, h = draw.textsize(text) draw.text((width - 5 - w, 110), text, colour,font=font) 

This is not so, about half of the words are outside the image area:

  colour = 'white' text = 'One-hand hammer' font = ImageFont.truetype("static/fonts/verdana.ttf", 10) draw = ImageDraw.Draw(base) w, h = draw.textsize(text) draw.text((width - 5 - w, 95), text, colour,font=font) 
+4
source share
1 answer

When calculating the width of the text, you will get an approximate value if the font is not taken into account (especially if you use a font of variable width).

To fix this, calculate the width of the text as follows:

 w, h = draw.textsize(text, font) 

Note that you may also need to adjust the size of the right margin to accommodate the new width calculation (five pixels are pretty small).

+4
source

Source: https://habr.com/ru/post/1385622/


All Articles