Ask Your Question
1

What is the correct method of aligning PIL text to the center?

asked 2022-03-19 11:00:00 +0000

lakamha gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2022-09-20 21:00:00 +0000

nofretete gravatar image

To align PIL text to the center, you can use the textwidth and textheight attributes of the font to calculate the position of the text. Here's an example:

from PIL import Image, ImageDraw, ImageFont

# Create a blank image
image = Image.new('RGB', (500, 500), 'white')

# Get a font
font = ImageFont.truetype('arial.ttf', 36)

# Get the size of the text
text = 'Hello, world!'
textwidth, textheight = draw.textsize(text, font)

# Calculate the position of the text
x = (image.width - textwidth) / 2
y = (image.height - textheight) / 2

# Draw the text
draw = ImageDraw.Draw(image)
draw.text((x, y), text, font=font, fill='black')

# Show the image
image.show()

This will create an image with the text "Hello, world!" centered horizontally and vertically.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-03-19 11:00:00 +0000

Seen: 12 times

Last updated: Sep 20 '22