Skip to content

Default anchor documentation incorrect for horizontal text (text and textbbox) #7586

@djhoese

Description

@djhoese

What did you do?

Read the documentation and the source code. I was mostly updating code to use textbbox instead of textsize and couldn't figure out why my text wasn't lining up the way I expected. The documentation for text and textbbox both say anchor defaults to "top left". This is only true for vertical (non-horizontal/) text.

https://pillow.readthedocs.io/en/stable/reference/ImageDraw.html#PIL.ImageDraw.ImageDraw.text

https://pillow.readthedocs.io/en/stable/reference/ImageDraw.html#PIL.ImageDraw.ImageDraw.textbbox

What did you expect to happen?

I expected similar results between the old textsize and the newer textbbox so I could adjust the position of the text for the old code I was updating. This old code adjusts the position rather than adjust the anchor to support multiple drawing backends (avoid passing anchor which other drawing backends might not understand).

What actually happened?

Unless I'm misreading the source code, the default anchor for horizontal text is "la":

Pillow/src/_imagingft.c

Lines 624 to 626 in 54c5631

if (anchor == NULL) {
anchor = horizontal_dir ? "la" : "lt";
}

What are your OS, Python and Pillow versions?

  • OS: Ubuntu
  • Python: 3.11
  • Pillow: 10.1.0
from PIL import Image, ImageDraw, ImageFont

font = ImageFont.load_default(size=40)
img = Image.new("RGB", (800, 800))
draw = ImageDraw.Draw(img)

text = "A"
pos = (400, 400)
bbox = draw.textbbox(pos, text, font, anchor="lt")
print("'lt' anchor bbox: ", bbox)
bbox = draw.textbbox(pos, text, font, anchor="la")
print("'la' anchor bbox: ", bbox)
bbox = draw.textbbox(pos, text, font)
print("Default anchor bbox: ", bbox)
'lt' anchor bbox:  (400, 400, 426, 428)
'la' anchor bbox:  (400, 411, 426, 439)
Default anchor bbox:  (400, 411, 426, 439)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions