使用 TrueType 字体
使用 TrueType 字体
本指南展示了如何使用 TtfInstancer 加载 TrueType 字体、检查其二进制表数据、读取原始表字节,并从可变字体创建静态实例。
TrueType (TTF) 字体是最常见的桌面和网络字体格式。Aspose.Font FOSS for Python 提供了 TtfFont,用于访问 TTF 特定的表数据、glyph blob 检索以及可变字体轴控制。
加载 TTF 字体
FontLoader.open() 自动检测 TTF 格式并返回一个 TtfFont 类型的对象。返回的实例提供对 TTF 特定功能的访问,例如 ttf_tables、get_table_bytes() 和可变字体轴数据。
from aspose_font import FontLoader
font = FontLoader.open("Roboto-Regular.ttf")
print(font.font_name, font.num_glyphs, "glyphs")访问 TTF 表
TtfFont.ttf_tables 提供了一个带有常用表命名属性的 TtfTableSet。
from aspose_font import FontLoader
from aspose_font import TtfFont
ttf_font: TtfFont = FontLoader.open("Roboto-Regular.ttf")
tables = ttf_font.ttf_tables
print("kern table present:", tables.kern is not None)原始表字节
使用 TtfFont.get_table_bytes(tag) 检索原始二进制表数据,使用 TtfFont.set_table_bytes(tag, data) 写入修改后的表字节。
from aspose_font import FontLoader
from aspose_font import TtfFont
ttf_font: TtfFont = FontLoader.open("Roboto-Regular.ttf")
raw_cmap = ttf_font.get_table_bytes("cmap")可变字体实例
TtfFont.get_axis(tag) 返回单个可变轴,使用其四字符标签(例如 "wght"、"wdth"),如果字体未定义该轴,则返回 None。TtfInstancer.instantiate() 在指定的轴坐标下从可变字体生成静态实例。
from aspose_font import FontLoader
from aspose_font import TtfFont
from aspose_font.ttf.instancer import TtfInstancer # internal API — may change between releases
ttf_font: TtfFont = FontLoader.open("Roboto-VariableFont_wdth,wght.ttf")
weight_axis = ttf_font.get_axis("wght")
if weight_axis is not None:
print(f"wght range: {weight_axis.min_value}-{weight_axis.max_value}")
# Get a static instance at wght=700, wdth=75
instance = TtfInstancer.instantiate(ttf_font, {"wght": 700.0, "wdth": 75.0})技巧与最佳实践
- 在访问
ttf_tables或get_table_bytes()之前,请始终使用isinstance(font, TtfFont) - 在读取字距对之前,使用
TtfTableSet.kern检查字距可用性 - 可变字体实例化会生成一个新的字体对象;原始对象保持不变
API Reference 概述
| 类 / 方法 | 描述 |
|---|---|
TtfFont.ttf_tables | 访问 TTF 表集 |
TtfFont.get_table_bytes(tag) | 命名表的原始字节 |
TtfFont.set_table_bytes(tag, data) | 写入已修改的表字节 |
TtfFont.get_axis(tag) | 按标签的可变字体轴,或 None |
TtfInstancer.instantiate(font, coords) | 创建静态实例 |
TtfTableSet.kern | 字距调整表(如果缺失则为 None) |