发布于 

Web使用HarmonyOS字体的压缩方案

HarmonyOS 字体

https://developer.harmonyos.com/cn/docs/design/font-0000001157868583

通过研究用户在不同场景下对多终端设备的阅读反馈,综合考量不同设备的尺寸、使用场景等因素,同时也考虑用户使用设备时因视距、视角的差异带来的字体大小和字重的不同诉求,我们为 HarmonyOS 设计了全新系统默认的字体——HarmonyOS Sans(即鸿蒙字体)。

HarmonyOS 字体效果
HarmonyOS 字体效果

通过 BILIBILI(哔哩哔哩)主站的使用效果来看,能明显发现 HarmonyOS 字体在 Windows 低分辨率pixel-ratio < 1.5屏幕上显示更加细腻。

网页加载速度的影响

如果需要全站使用同一种字体,那么我们或许需要同时加载 Regular、Medium、Bold 等不同字重的字体文件,这里给一个参考:
HarmonyOS_Sans_SC_Regular.ttf 文件大小高达 8068KB,注意,这仅仅是 Regular。
所以,如果不对字体文件进行压缩,将其作为 Web 字体是不合理的,这将极大拉缓网页加载速度,严重影响用户体验。

字体压缩

FontTools

What is this?

fontTools is a library for manipulating fonts, written in Python. The project includes the TTX tool, that can convert TrueType and OpenType fonts to and from an XML text format, which is also called TTX. It supports TrueType, OpenType, AFM and to an extent Type 1 and some Mac-specific formats. The project has an MIT open-source licence.

Among other things this means you can use it free of charge.

User documentation and developer documentation are available at Read the Docs.

如何压缩

借助以上工具,我们可以将 unicode 分为多个片段来对字体文件进行压缩:

字符集 字数 Unicode 编码
拉丁字母 0000-007F,0080-00FF等
基本汉字 20902 字 4E00-9FA5
中文字符 3002,FF1F等

我们只需要对这两万多个基本汉字进行分段即可,至于数字、拉丁字母等,其实并不会过多影响字体文件大小。

将 unicode 合理分段后,使用 fonttools subset 对字体进行压缩,命令如下:

1
2
3
4
5
6
7
pyftsubset ./HarmonyOS_Sans_SC_Bold.ttf --unicodes-file=./unicodes_10.txt --with-zopfli --flavor=woff2

# 参数
# pyftsubset <PATH> # 待压缩字体文件路径
# --unicodes-file=<PATH> # unicode.txt 文件路径
# --with-zopfli # 使用 Google 压缩算法
# --flavor=<TYPE> # 输出字体格式

我们将 unicode 写入 unicode.txt 文件中,使用 --unicodes-file=<PATH>即可使用。
待所有字体压缩完成后,我们在 CSS 中使用 unicode-range属性来调用对应 unicode 区域的字体文件。

具体效果可参考本站的字体显示情况。