83 lines
2.6 KiB
Python
83 lines
2.6 KiB
Python
"""
|
|
字体工具 - 用于处理中文字体
|
|
"""
|
|
|
|
import os
|
|
from PIL import ImageFont
|
|
|
|
def get_chinese_font(font_size=14):
|
|
"""获取中文字体
|
|
|
|
Args:
|
|
font_size: 字体大小
|
|
|
|
Returns:
|
|
ImageFont对象
|
|
"""
|
|
# 中文字体路径列表(按优先级排序)
|
|
chinese_fonts = [
|
|
# 文泉驿字体
|
|
'/usr/share/fonts/truetype/wqy/wqy-zenhei.ttc',
|
|
# Noto Sans CJK
|
|
'/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc',
|
|
'/usr/share/fonts/opentype/noto/NotoSansCJK-Bold.ttc',
|
|
# 其他可能的中文字体
|
|
'/usr/share/fonts/truetype/arphic/uming.ttc',
|
|
'/usr/share/fonts/truetype/arphic/ukai.ttc',
|
|
]
|
|
|
|
for font_path in chinese_fonts:
|
|
if os.path.exists(font_path):
|
|
try:
|
|
return ImageFont.truetype(font_path, font_size)
|
|
except Exception as e:
|
|
print(f'字体加载失败 {font_path}: {e}')
|
|
continue
|
|
|
|
# 如果找不到中文字体,使用默认字体
|
|
print('⚠️ 未找到中文字体,使用默认字体')
|
|
return ImageFont.load_default()
|
|
|
|
def setup_matplotlib_chinese():
|
|
"""设置matplotlib支持中文显示"""
|
|
try:
|
|
import matplotlib.pyplot as plt
|
|
import matplotlib
|
|
|
|
# 查找中文字体
|
|
font_path = None
|
|
for path in [
|
|
'/usr/share/fonts/truetype/wqy/wqy-zenhei.ttc',
|
|
'/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc'
|
|
]:
|
|
if os.path.exists(path):
|
|
font_path = path
|
|
break
|
|
|
|
if font_path:
|
|
# 添加字体到matplotlib
|
|
import matplotlib.font_manager as fm
|
|
fm.fontManager.addfont(font_path)
|
|
font_name = fm.FontProperties(fname=font_path).get_name()
|
|
|
|
# 设置中文字体
|
|
plt.rcParams['font.sans-serif'] = [font_name]
|
|
plt.rcParams['axes.unicode_minus'] = False
|
|
print(f'✅ matplotlib已设置中文字体: {font_name}')
|
|
return True
|
|
else:
|
|
print('⚠️ 未找到matplotlib可用的中文字体')
|
|
return False
|
|
|
|
except Exception as e:
|
|
print(f'❌ matplotlib中文设置失败: {e}')
|
|
return False
|
|
|
|
# 预加载字体
|
|
CHINESE_FONT = get_chinese_font(14)
|
|
MATPLOTLIB_CHINESE_SETUP = setup_matplotlib_chinese()
|
|
|
|
if __name__ == '__main__':
|
|
print('字体工具测试:')
|
|
print(f'中文字体: {CHINESE_FONT}')
|
|
print(f'matplotlib中文支持: {MATPLOTLIB_CHINESE_SETUP}') |