0

As the title says, I want to centre multiline text onto a created image using PIL. I have used this code - https://stackoverflow.com/a/1970942/7286028 but it only uses a middle-vertical align. I, however, want to have vertical and horizontal align. This should be easy but it complicated by padding pixels and other factors.

Thanks for any help, Louis

1 Answers1

1

Both the frame and the text are centred around the top left hand corner and each offset is in pixels.

the value W is the width of the frame and H is the height of the frame.

the value w is the width of the text and h is the height of the text.

Top Left: draw.text((0, 0), msg, fill="black")

Top Right: draw.text((W-w, 0), msg, fill="black")

Bottom Left: draw.text((0, H-h), msg, fill="black")

Bottom Right: draw.text((W-w, H-h), msg, fill="black")

You can then use this idea to have the text a fraction of the distance along like halfway with both with this method (seen in the linked discussion):

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

finally adding padding of a certain amount of pixels can be done by adding/subtracting an integer from the code:

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

Github Link: https://github.com/Oliver-Tafe/StackOverflow/blob/master/PillowTextAlign.py

Oliver Tafe
  • 126
  • 1
  • 5