add getbbox and getlength to TransposedFont with tests

This commit is contained in:
nulano 2022-06-20 02:18:16 +01:00
parent e2158344a0
commit 93acbcf9e2
No known key found for this signature in database
GPG Key ID: B650CDF63B705766
2 changed files with 50 additions and 4 deletions

View File

@ -315,16 +315,31 @@ class TestImageFont:
# Original font
draw.font = font
with pytest.warns(DeprecationWarning) as log:
box_size_a = draw.textsize(word)
assert len(log) == 1
bbox_a = draw.textbbox((10, 10), word)
# Rotated font
draw.font = transposed_font
with pytest.warns(DeprecationWarning) as log:
box_size_b = draw.textsize(word)
assert len(log) == 1
bbox_b = draw.textbbox((20, 20), word)
# Check (w,h) of box a is (h,w) of box b
assert box_size_a[0] == box_size_b[1]
assert box_size_a[1] == box_size_b[0]
# Check bbox b is (20, 20, 20 + h, 20 + w)
assert bbox_b[0] == 20
assert bbox_b[1] == 20
assert bbox_b[2] == 20 + bbox_a[3] - bbox_a[1]
assert bbox_b[3] == 20 + bbox_a[2] - bbox_a[0]
# text length is undefined for vertical text
pytest.raises(ValueError, draw.textlength, word)
def test_unrotated_transposed_font(self):
img_grey = Image.new("L", (100, 100))
draw = ImageDraw.Draw(img_grey)
@ -336,15 +351,31 @@ class TestImageFont:
# Original font
draw.font = font
with pytest.warns(DeprecationWarning) as log:
box_size_a = draw.textsize(word)
assert len(log) == 1
bbox_a = draw.textbbox((10, 10), word)
length_a = draw.textlength(word)
# Rotated font
draw.font = transposed_font
with pytest.warns(DeprecationWarning) as log:
box_size_b = draw.textsize(word)
assert len(log) == 1
bbox_b = draw.textbbox((20, 20), word)
length_b = draw.textlength(word)
# Check boxes a and b are same size
assert box_size_a == box_size_b
# Check bbox b is (20, 20, 20 + w, 20 + h)
assert bbox_b[0] == 20
assert bbox_b[1] == 20
assert bbox_b[2] == 20 + bbox_a[2] - bbox_a[0]
assert bbox_b[3] == 20 + bbox_a[3] - bbox_a[1]
assert length_a == length_b
def test_rotated_transposed_font_get_mask(self):
# Arrange
text = "mask this"

View File

@ -853,6 +853,21 @@ class TransposedFont:
return im.transpose(self.orientation)
return im
def getbbox(self, text, *args, **kwargs):
# TransposedFont doesn't support getmask2, move top-left point to (0, 0)
# this has no effect on ImageFont and simulates anchor="lt" for FreeTypeFont
left, top, right, bottom = self.font.getbbox(text, *args, **kwargs)
width = right - left
height = bottom - top
if self.orientation in (Image.Transpose.ROTATE_90, Image.Transpose.ROTATE_270):
return 0, 0, height, width
return 0, 0, width, height
def getlength(self, text, *args, **kwargs):
if self.orientation in (Image.Transpose.ROTATE_90, Image.Transpose.ROTATE_270):
raise ValueError("text length is undefined for rotated text")
return self.font.getlength(text, *args, **kwargs)
def load(filename):
"""