Skip to content

Add an example of filtering pre-installed fonts by language #2592

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
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
88 changes: 88 additions & 0 deletions examples/font_filter_by_language.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
"""
This example demonstrates how to find fonts for each language.
"""

from typing import Iterator

from pygame.font import get_fonts
from pygame import freetype
import pygame


def enum_font_from_lang(lang) -> Iterator[str]:
"""
Enumerates fonts that are suitable for a specified language.
"""
text = DISCRIMINANTS[lang]
for font_name in get_fonts():
if can_render_text(font_name, text):
yield font_name


def can_render_text(font_name, text, *, font_size=14) -> bool:
"""
Whether a specified font is capable of rendering a specified text.

The result of this function is not guaranteed to be correct due to its
implementation strategy.
"""
try:
font = freetype.SysFont(font_name, font_size)
except AttributeError as e:
# AttributeError occurs on certain fonts, which may be a PyGame bug.
if e.args[0] == r"this style is unsupported for a bitmap font":
return False
else:
raise
rendered = []
for c in text:
pixels = font.render_raw(c)
if pixels in rendered:
return False
rendered.append(pixels)
return True


DISCRIMINANTS = {
"ja": "経伝説あAB",
"ko": "안녕조AB",
"zh-Hans": "哪经传说AB",
"zh-Hant": "哪經傳說AB",
"zh": "哪經傳說经传说AB",
}
"""
You may have noticed the 'AB' in the values of this dictionary.
If you don't include ASCII characters, you might choose a font that cannot
render them, such as a fallback font, which is probably not what you want.
"""


def main():
pygame.init()

screen = pygame.display.set_mode((800, 800))
screen.fill("white")
x, y = 40, 10
spacing = 10
for font_name in enum_font_from_lang("ja"):
font = freetype.SysFont(font_name, 30)
rect = font.render_to(screen, (x, y), "経伝説 한글 经传说 ABC 經傳說 あいう")
y = y + rect.height + spacing
pygame.display.flip()

clock = pygame.time.Clock()
running = True

while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
running = False
clock.tick(4)

pygame.quit()


if __name__ == "__main__":
main()