add textbbox and textlength to ImageDraw2 and update tests

This commit is contained in:
nulano 2022-05-25 22:00:13 +01:00
parent f34a6460ef
commit 1bf87556ef
No known key found for this signature in database
GPG Key ID: B650CDF63B705766
3 changed files with 35 additions and 6 deletions

View File

@ -1239,7 +1239,7 @@ def test_textsize_empty_string():
@skip_unless_feature("freetype2")
def test_textsize_stroke():
def test_textbbox_stroke():
# Arrange
im = Image.new("RGB", (W, H))
draw = ImageDraw.Draw(im)

View File

@ -1,5 +1,7 @@
import os.path
import pytest
from PIL import Image, ImageDraw, ImageDraw2
from .helper import (
@ -205,7 +207,9 @@ def test_textsize():
font = ImageDraw2.Font("white", FONT_PATH)
# Act
size = draw.textsize("ImageDraw2", font)
with pytest.warns(DeprecationWarning) as log:
size = draw.textsize("ImageDraw2", font)
assert len(log) == 1
# Assert
assert size[1] == 12
@ -221,9 +225,10 @@ def test_textsize_empty_string():
# Act
# Should not cause 'SystemError: <built-in method getsize of
# ImagingFont object at 0x...> returned NULL without setting an error'
draw.textsize("", font)
draw.textsize("\n", font)
draw.textsize("test\n", font)
draw.textbbox((0, 0), "", font)
draw.textbbox((0, 0), "\n", font)
draw.textbbox((0, 0), "test\n", font)
draw.textlength("", font)
@skip_unless_feature("freetype2")

View File

@ -25,6 +25,7 @@
from . import Image, ImageColor, ImageDraw, ImageFont, ImagePath
from ._deprecate import deprecate
class Pen:
@ -176,4 +177,27 @@ class Draw:
.. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.textsize`
"""
return self.draw.textsize(text, font=font.font)
deprecate("textsize", 10, "textbbox or textlength")
return self.draw.textsize(text, font=font.font, __internal__=True)
def textbbox(self, xy, text, font):
"""
Returns bounding box (in pixels) of given text.
:return: ``(left, top, right, bottom)`` bounding box
.. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.textbbox`
"""
if self.transform:
xy = ImagePath.Path(xy)
xy.transform(self.transform)
return self.draw.textbbox(xy, text, font=font.font)
def textlength(self, text, font):
"""
Returns length (in pixels) of given text.
This is the amount by which following text should be offset.
.. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.textlength`
"""
return self.draw.textlength(text, font=font.font)