如何检测当前字体是否包含指定 Unicode?

解读

在 Matplotlib 中,**“当前字体”**并不是系统里随便装的那一款,而是经过三层过滤后的最终候选:

  1. 用户通过 rcParams['font.family'] 或 font_manager.FontProperties 显式指定的族;
  2. Matplotlib 的 fontManager 在磁盘缓存(~/.cache/matplotlib/fontlist-*.json)里按 “语言→风格→得分” 排序后的列表;
  3. 渲染后端(Agg/PDF/SVG)在真正绘制时,调用 ft2font(C++ 封装 FreeType)加载的 单个 FT_Face。

因此,“检测”必须发生在第 3 步之后,否则会出现“系统里有、Matplotlib 没匹配到”或“匹配到但 FreeType 加载失败”的假阴性。
国内面试常追问:

  • 如何不画图就提前知道?
  • 如何批量检测中日韩生僻字(CJK ExtB)?
  • 如果返回 False,如何自动降级到思源黑体?
    回答时必须给出 “Python 层 + C++ 层” 两条通路,并说明缓存机制,否则会被认为“只懂调库”。

知识点

  1. font_manager.py:findfont(..., fallback_to_default=False) 可强制抛出异常,避免回退到 DejaVu Sans。
  2. ft2font.cpp:FT_Get_Char_Index(face, unicode) 返回 0 表示缺字;这是 Matplotlib 渲染时实际走的函数。
  3. get_text_path_width_height 调用链:
    textobj.get_window_extent → renderer.get_text_width_height_descent → ft2font.load_char;
    一旦 FT_Get_Char_Index==0,Matplotlib 会记录 matplotlib._text_layout.log.warning('Missing glyph...'),但默认不抛异常。
  4. Unicode 区段:CJK Unified Ideographs Extension B(U+20000–U+2A6DF)需要 OTF 的 cmap format 12,老版本 FreeType 会解析失败;国内项目需验证 ft2font.FT_Face.get_charmap_format()。
  5. 缓存一致性:若用户动态安装新字体,必须执行 font_manager._rebuild() 并删除 ~/.cache/matplotlib/*.json,否则 findfont 仍返回旧路径。
  6. PEP8 边界:检测函数应返回 bool,并在 docstring 中标注 “Raises RuntimeError if FreeType < 2.10”,方便 CI 捕获。

答案

import matplotlib
from matplotlib import font_manager
from matplotlib.ft2font import FT2Font

def unicode_in_current_font(ucs: str) -> bool:
    """
    检测 *当前 rcParams 字体* 是否包含指定 Unicode 码位。
    参数
    ----
    ucs : str
        长度为 1 的 Unicode 字符。
    返回
    ----
    bool
        True  -> 字体包含该字形;
        False -> 字体缺失该字形;
    异常
    ----
    RuntimeError
        当系统无可用字体或 FreeType 版本过低时抛出。
    """
    if len(ucs) != 1:
        raise ValueError('只接受单个字符')
    code = ord(ucs)

    # 1. 找到 Matplotlib 最终渲染时会用的那个 ttf/otf 文件
    try:
        font_path = font_manager.findfont(
            font_manager.FontProperties(
                family=matplotlib.rcParams['font.family']),
            fallback_to_default=False)
    except ValueError as e:
        raise RuntimeError('无匹配字体') from e

    # 2. 用与 Agg 后端相同的 C++ 接口加载
    face = FT2Font(font_path)
    # 3. FreeType 返回 0 表示缺字
    return face.get_char_index(code) != 0


# 使用示例
if __name__ == '__main__':
    matplotlib.rcParams['font.family'] = 'SimHei'
    print(unicode_in_current_font('你'))   # True
    print(unicode_in_current_font('𠮷'))  # False,需思源黑体

关键点:

  • 必须关闭 fallback_to_default,否则 SimHei 找不到时会偷偷返回 DejaVu Sans,导致误判。
  • FT2Font 对象与 Agg 渲染器共用同一份 FreeType 上下文,结论与真实绘制完全一致。
  • 若返回 False,可再调用 font_manager.findfont('Source Han Sans SC') 实现 自动降级。

拓展思考

  1. 批量检测:对 10 万 CJK extB 字符,可一次性把 face.get_char_index 结果做成 位图数组,内存占用 < 2 MB,比 Python for 循环快两个数量级;国内古籍数字化项目常用此法预筛字体。
  2. WebGL 后端:JupyterLab 的 ipympl 使用 wasm-freetype,接口相同,但路径变成 /static/fonts/...,需通过 matplotlib.get_cachedir() 区分本地与浏览器缓存。
  3. GPU 加速:在 mplcairo 后端,cairo 的 scaled_font.text_to_glyphs 同样返回 0 表示缺字;若未来 Matplotlib 支持 GPU glyph cache,检测函数需再封装一层 cairo_font_face_t。
  4. 合规风险:国内商业报表若因字体缺字导致 □ 乱码,可能被监管认定为数据缺失;因此上线前需在 CI 中跑一遍 unicode_in_current_font 对全量字符做 单元测试,并归档报告。