Reputation: 3802
I use PIL to draw some text on the image.
I did as in this example Center-/middle-align text with PIL? and it worked, however, when the text phrase changes the lines are not aligned.
Font is Verdana. Where could be the problem?
This displays correctly 5 pixels from 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 does not, about a 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)
Upvotes: 4
Views: 3925
Reputation: 120568
When calculating the width of text, you will only get an approximation if the font is not taken into account (especially if you use a variable-width font).
To fix this, calculate the text width like this:
w, h = draw.textsize(text, font)
Note that you may also need to adjust the size of the right-margin to take account of the new width calculation (five pixels is pretty small).
Upvotes: 4