Files
pbz-progress-roadmap/fonts.py
T

50 lines
1.5 KiB
Python

"""跨平台中文字体查找(Windows / macOS / Linux)。"""
from pathlib import Path
from PIL import ImageFont
CANDIDATES = [
# Windows
r"C:\Windows\Fonts\msyh.ttc",
r"C:\Windows\Fonts\msyhbd.ttc",
r"C:\Windows\Fonts\simhei.ttf",
r"C:\Windows\Fonts\NotoSansSC-Regular.otf",
# macOS
"/System/Library/Fonts/PingFang.ttc",
"/System/Library/Fonts/Hiragino Sans GB.ttc",
"/Library/Fonts/Arial Unicode.ttf",
# Linux
"/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc",
"/usr/share/fonts/truetype/noto/NotoSansCJK-Regular.ttc",
"/usr/share/fonts/truetype/wqy/wqy-zenhei.ttc",
"/usr/share/fonts/truetype/arphic/uming.ttc",
]
_cache: dict[int, ImageFont.FreeTypeFont | ImageFont.ImageFont] = {}
def font(size: int):
"""按字号取一个能显示中文的字体;全找不到则退回默认位图字体。"""
if size in _cache:
return _cache[size]
for p in CANDIDATES:
try:
f = ImageFont.truetype(p, size)
_cache[size] = f
return f
except Exception:
continue
f = ImageFont.load_default()
_cache[size] = f
return f
def warn_if_missing():
"""没有任何 CJK 字体时提示用户,否则图里中文会变方块。"""
for p in CANDIDATES:
if Path(p).exists():
return True
print("警告:没找到中文字体,图中中文可能显示为方块。\n"
" Linux 可安装:sudo apt install fonts-noto-cjk", file=__import__("sys").stderr)
return False