46 lines
1.6 KiB
Python
46 lines
1.6 KiB
Python
#!/usr/bin/env python3
|
|
# -*- coding: utf-8 -*-
|
|
"""自带NotoSansCJK中文字体,完全不依赖系统"""
|
|
import os
|
|
import sys
|
|
from PIL import ImageFont
|
|
|
|
# 字体文件路径(项目内置开源无版权NotoSansCJK精简版)
|
|
FONT_DIR = os.path.join(os.path.dirname(__file__), "assets", "fonts")
|
|
BOLD_FONT = os.path.join(FONT_DIR, "NotoSansCJK-Bold.ttc")
|
|
REGULAR_FONT = os.path.join(FONT_DIR, "NotoSansCJK-Regular.ttc")
|
|
|
|
def get_chinese_font(size: int, bold: bool = False) -> ImageFont.FreeTypeFont:
|
|
"""优先使用项目内置字体,完全兼容所有系统"""
|
|
try:
|
|
if bold and os.path.exists(BOLD_FONT):
|
|
return ImageFont.truetype(BOLD_FONT, size)
|
|
elif not bold and os.path.exists(REGULAR_FONT):
|
|
return ImageFont.truetype(REGULAR_FONT, size)
|
|
except Exception:
|
|
pass
|
|
|
|
# 内置字体找不到,再尝试系统字体
|
|
font_candidates = [
|
|
# Windows
|
|
"simhei.ttf" if bold else "simsun.ttc",
|
|
"msyh.ttc" if bold else "msyh.ttf",
|
|
# Linux
|
|
"/usr/share/fonts/opentype/noto/NotoSansCJK-Bold.ttc" if bold else "/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc",
|
|
"/usr/share/fonts/truetype/arphic/uming.ttc",
|
|
# macOS
|
|
"/System/Library/Fonts/PingFang.ttc" if bold else "/System/Library/Fonts/STHeiti Light.ttc",
|
|
]
|
|
|
|
for font_name in font_candidates:
|
|
try:
|
|
return ImageFont.truetype(font_name, size)
|
|
except Exception:
|
|
pass
|
|
|
|
# 最后 fallback
|
|
return ImageFont.load_default(size)
|
|
|
|
# 自动创建assets/fonts目录
|
|
os.makedirs(FONT_DIR, exist_ok=True)
|