Skip to content

Commit 4cf281b

Browse files
committed
Added set_variation_by_name_index
1 parent 76d6228 commit 4cf281b

File tree

2 files changed

+22
-1
lines changed

2 files changed

+22
-1
lines changed

Tests/test_imagefont.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -753,6 +753,8 @@ def test_variation_duplicates() -> None:
753753
b"Black",
754754
b"Black Medium Contrast",
755755
b"Black High Contrast",
756+
b"Black High Contrast",
757+
b"Black High Contrast",
756758
b"Default",
757759
]
758760

@@ -791,6 +793,18 @@ def test_variation_set_by_name(font: ImageFont.FreeTypeFont) -> None:
791793
_check_text(font, "Tests/images/variation_tiny_name.png", 40)
792794

793795

796+
def test_variation_set_by_name_index(font: ImageFont.FreeTypeFont) -> None:
797+
with pytest.raises(OSError):
798+
font.set_variation_by_name_index(0)
799+
800+
font = ImageFont.truetype("Tests/fonts/AdobeVFPrototype.ttf", 36)
801+
_check_text(font, "Tests/images/variation_adobe.png", 11)
802+
index = font.get_variation_names().index(b"Bold")
803+
font.set_variation_by_name_index(index)
804+
assert font.getname()[1] == "Bold"
805+
_check_text(font, "Tests/images/variation_adobe_name.png", 16)
806+
807+
794808
def test_variation_set_by_axes(font: ImageFont.FreeTypeFont) -> None:
795809
with pytest.raises(OSError):
796810
font.set_variation_by_axes([500, 50])

src/PIL/ImageFont.py

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -686,7 +686,14 @@ def set_variation_by_name(self, name: str | bytes) -> None:
686686
names = self.get_variation_names()
687687
if not isinstance(name, bytes):
688688
name = name.encode()
689-
index = names.index(name) + 1
689+
self.set_variation_by_name_index(names.index(name))
690+
691+
def set_variation_by_name_index(self, index: int) -> None:
692+
"""
693+
:param name: The index within the list of named styles in a variation font.
694+
:exception OSError: If the font is not a variation font.
695+
"""
696+
index += 1
690697

691698
if index == getattr(self, "_last_variation_index", None):
692699
# When the same name is set twice in a row,

0 commit comments

Comments
 (0)