Skip to content

Max width for text like in canvas #9076

Answered by radarhere
Nazar1ky asked this question in Q&A
Discussion options

You must be logged in to vote

We don't have an API specifically for that purpose, but users can still use our other APIs to achieve the end result.

from PIL import Image, ImageDraw, ImageFont
im = Image.new("RGB", (250, 150), "#fff")
d = ImageDraw.Draw(im)
font = ImageFont.load_default(size=48)

# Normal
d.text((0, 0), "Hello world", "#000", font)

# With max-width
maxwidth = 100
left, top, right, bottom = d.textbbox((0, 0), "Hello world", font)
width = right - left
if width > maxwidth:
    im2 = Image.new("RGBA", (right, bottom))
    d = ImageDraw.Draw(im2)
    d.text((0, 0), "Hello world", "#000", font)
    im2 = im2.resize((maxwidth, bottom))
    im.paste(im2, (0, 75), mask=im2)
else:
    d.text((0, 75), "Hello world"

Replies: 1 comment 1 reply

Comment options

You must be logged in to vote
1 reply
@Nazar1ky
Comment options

Answer selected by Nazar1ky
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants