Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions Tests/test_imagefont.py
Original file line number Diff line number Diff line change
Expand Up @@ -753,6 +753,8 @@ def test_variation_duplicates() -> None:
b"Black",
b"Black Medium Contrast",
b"Black High Contrast",
b"Black High Contrast",
b"Black High Contrast",
b"Default",
]

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


def test_variation_set_by_name_index(font: ImageFont.FreeTypeFont) -> None:
with pytest.raises(OSError):
font.set_variation_by_name_index(0)

font = ImageFont.truetype("Tests/fonts/AdobeVFPrototype.ttf", 36)
_check_text(font, "Tests/images/variation_adobe.png", 11)
index = font.get_variation_names().index(b"Bold")
font.set_variation_by_name_index(index)
assert font.getname()[1] == "Bold"
_check_text(font, "Tests/images/variation_adobe_name.png", 16)


def test_variation_set_by_axes(font: ImageFont.FreeTypeFont) -> None:
with pytest.raises(OSError):
font.set_variation_by_axes([500, 50])
Expand Down
17 changes: 10 additions & 7 deletions src/PIL/ImageFont.py
Original file line number Diff line number Diff line change
Expand Up @@ -675,12 +675,8 @@ def get_variation_names(self) -> list[bytes]:
:returns: A list of the named styles in a variation font.
:exception OSError: If the font is not a variation font.
"""
names = []
for name in self.font.getvarnames():
name = name.replace(b"\x00", b"")
if name not in names:
names.append(name)
return names
names = self.font.getvarnames()
return [name.replace(b"\x00", b"") for name in names]

def set_variation_by_name(self, name: str | bytes) -> None:
"""
Expand All @@ -690,7 +686,14 @@ def set_variation_by_name(self, name: str | bytes) -> None:
names = self.get_variation_names()
if not isinstance(name, bytes):
name = name.encode()
index = names.index(name) + 1
self.set_variation_by_name_index(names.index(name))

def set_variation_by_name_index(self, index: int) -> None:
"""
:param name: The index within the list of named styles in a variation font.
:exception OSError: If the font is not a variation font.
"""
index += 1

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