首次提交

This commit is contained in:
zwf
2026-06-02 16:26:10 +08:00
commit 291e6fcaae
79 changed files with 11283 additions and 0 deletions
+58
View File
@@ -0,0 +1,58 @@
from matplotlib import pyplot as plt
from matplotlib.font_manager import fontManager, FontProperties
def get_fonts():
"""
取得系统字体,并与要采用的字体合并后,取得可用字体。
"""
# 系统所有可用字体
os_fonts = {f.name for f in fontManager.ttflist}
# 自定义字体,优先级按顺序排列
custom_fonts = (
'PingFang SC', 'Hiragino Sans GB', 'Heiti SC', 'SimSong', 'SimHei',
'WenQuanYi Micro Hei', 'WenQuanYi Zen Hei', 'Source Han Sans SC',
'Noto Sans CJK', 'Noto Sans CJK SC', 'DejaVu Sans'
)
# 可用字体
available_font = set(custom_fonts) & os_fonts
# 字典排序
available_font = sorted(
available_font, key=lambda x: custom_fonts.index(x) if x in custom_fonts else len(custom_fonts)
)
return available_font
def get_font_metrics(font_name='Microsoft YaHei', font_size=11, dpi=72):
"""
使用 matplotlib 获取字体度量信息。
:param font_name: 字体名称
:param font_size: 字号
:param dpi: 显示像素,像素没英寸
:return: (英文字符宽度_cm, 中文字符宽度_cm)
"""
# 创建高分辨率图形
fig = plt.figure(figsize=(10, 2), dpi=dpi)
ax = fig.add_subplot(111)
ax.axis('off')
# 设置字体
font = FontProperties(family=font_name, size=font_size)
# 测试英文字符
text_en = ax.text(0.1, 0.5, 'aaaaa', fontproperties=font)
fig.canvas.draw()
en_width_px = text_en.get_window_extent().width / 5 # 5个字符的平均宽度
# 测试中文字符
text_cn = ax.text(0.1, 0.5, '中中中中中', fontproperties=font)
fig.canvas.draw()
cn_width_px = text_cn.get_window_extent().width / 5 # 5个字符的平均宽度
plt.close(fig)
# 转换为厘米
px_per_cm = dpi / 2.54
# 增加100%宽度
return en_width_px / px_per_cm * 2, cn_width_px / px_per_cm * 2