为NexT主题启用HarmonyOS Sans字体

博客试用过过多种字体,如思源黑体、思源宋体等。虽然它们都是可以免费商用的字体,但在字形上存在不完美之处,强迫症表示无法接受。首先,不管是半角还是全角状态下,打出来的都是全角单引号,在一堆英文里面出现一个全角的单引号违和感过于强烈。其次是一些汉字的笔画间距有问题,一个例子就是思源宋体的些字,上方的“此”和下半部分的“二”挨得太近,看着很别扭。最近华为推出了HarmonyOS,我也在我的Mate20上面尝鲜了一下,发现它自带的HarmonyOS Sans字体看着更加顺眼,同时这个字体也是可以免费商用的,因此打算给论坛也换上这个字体。

获取字体

可以在鸿蒙开发者官网下载:https://developer.harmonyos.com/cn/docs/design/des-resources/general-0000001157315901 ,选择HarmonyOS Sans。

转码

字体包只提供了TTF格式的字体文件,无法直接嵌入到博客页面里面,需要转码成WOFF和WOFF2格式(据说只转码WOFF2即可,我没测试)。之前测试过在aconvert.com转码,转码WOFF正常但转码WOFF2会卡住。在cloudconvert转码成功。一般只需要常规(Regular)和粗体(Bold)两个字重。

每个字体文件在4-5M左右,对加载速度无明显影响。

WOFF/WOFF2格式下载:https://pan.baidu.com/s/1SABUWCJAAkp8KxTaXX3Eng 提取码: 2bgs

应用

在主题配置文件_config.yml中启用自定义样式变量,允许对source/_data/styles.styl的引用。这个文件一般在Hexo根目录/node_modules/hexo-theme-next下面。

1
2
3
4
5
6
7
8
9
10
11
custom_file_path:
#head: source/_data/head.njk
#header: source/_data/header.njk
#sidebar: source/_data/sidebar.njk
#postMeta: source/_data/post-meta.njk
#postBodyEnd: source/_data/post-body-end.njk
#footer: source/_data/footer.njk
#bodyEnd: source/_data/body-end.njk
#variable: source/_data/variables.styl
#mixin: source/_data/mixins.styl
style: source/_data/styles.styl

Hexo根目录/source/下面创建fonts文件夹,将4个字体文件拷进去。

创建Hexo根目录/source/_data/styles.styl文件,输入以下内容并保存:

1
2
3
4
5
6
7
8
9
10
11
12
13
@font-face {
font-family: 'HarmonyOSSansSC';
src: url('/fonts/HarmonyOS_Sans_SC_Regular.woff2') format('woff2'),
url('/fonts/HarmonyOS_Sans_SC_Regular.woff') format('woff');
font-weight: 400;
}

@font-face {
font-family: 'HarmonyOSSansSC';
src: url('/fonts/HarmonyOS_Sans_SC_Bold.woff2') format('woff2'),
url('/fonts/HarmonyOS_Sans_SC_Bold.woff') format('woff');
font-weight: 700;
}

回到_config.yml,定位到“font:”,修改该条目下的属性为:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# Global font settings used for all elements inside <body>.
global:
external: true
family: HarmonyOSSansSC
size:

# Font settings for site title (.site-title).
title:
external: true
family: HarmonyOSSansSC
size:

# Font settings for headlines (<h1> to <h6>).
headings:
external: true
family: HarmonyOSSansSC
size:

# Font settings for posts (.post-body).
posts:
external: true
family: HarmonyOSSansSC

这将把博客名称、文章标题、章节、正文的字体全部替换成HarmonyOS Sans SC。

最后执行一遍hexo cleanhexo d,打开浏览器按Ctrl+F5强制刷新即可生效。

效果

Windows 100%:

Windows 150%:

$ EOF.