6

I want to know how can I draw text like this check image

As you can see text is on a green image and text has pink color background

My code, this is part of my code I'm using PIL

        draw = ImageDraw.Draw(background)
        font = ImageFont.truetype("assets/font2.ttf", 40)
        font2 = ImageFont.truetype("assets/font2.ttf", 70)
        arial = ImageFont.truetype("assets/font2.ttf", 30)
        name_font = ImageFont.truetype("assets/font.ttf", 30)
        para = textwrap.wrap(title, width=32)
        j = 0
        draw.text(
            (10, 10), f"{h}", fill="red", font=name_font
        )
        draw.text(
            (600, 150),
            "NOW PLAYING",
            fill="white",
            stroke_width=2,
            stroke_fill="white",
            font=font2,
        )

Thanks in advance :-)

  • Does this help? https://stackoverflow.com/questions/2498875/how-to-invert-colors-of-image-with-pil-python-imaging – MSH May 15 '22 at 18:25

1 Answers1

14

You can use the draw.textbbox method to get a bounding box for your text string and fill it using the draw.rectangle method.

from PIL import Image, ImageDraw, ImageFont

image = Image.new("RGB", (500, 100), "white")
font = ImageFont.truetype("segoeui.ttf", 40)
draw = ImageDraw.Draw(image)
position = (10, 10)
text = "Hello world"

bbox = draw.textbbox(position, text, font=font)
draw.rectangle(bbox, fill="red")
draw.text(position, text, font=font, fill="black")

image.show()

Example 1, black text on red rectangle

If you want a larger margin for the background rectangle, you can adjust the returned bounding box like so:

left, top, right, bottom = draw.textbbox(position, text, font=font)
draw.rectangle((left-5, top-5, right+5, bottom+5), fill="red")
draw.text(position, text, font=font, fill="black")

Example 2, wider rectangle in background

Nulano
  • 1,148
  • 13
  • 27
  • 1
    Thanks for this. Just a quick tip, if you want to center align the textbox, pass the attribute `anchor="mm"`. Further explanation of anchor attribute: https://pillow.readthedocs.io/en/stable/handbook/text-anchors.html#text-anchors – English Rain Sep 24 '22 at 07:04