字体管理
本文主要介绍一下常规的几种 font 管理方式
请指出文中任何不严谨之处,感谢!
目录
引子
前端开发过程中,对于字体的管理,是绕不开的内容,简单但是有一定的规范。
主要包括对单一字体不同粗细度的管理以及对不同字体的管理。
其中,有人可能会好奇,对于单一字体的粗细度,我直接使用 font-weight 控制不香吗?
错,起初我也是这么认为,但是实际开发过后,我发现不同平台(浏览器差异、pc 和移动端的差异等)对 font-weight 的渲染是不一样的。尤其是对于 UI 有严格把控的企业级样式,可能代码和设计稿的 font-weight 是一样的,但是渲染效果就是不一样,你说这可咋办。
因此,对于字体,基本是要对不同粗细度(常用的就几个,thin、normal、medium、bold,各自对应固定的设计稿数值)的字体进行下载,并进行管理和应用,确保渲染不会差异过大。
本文主要侧重点也是单一字体的不同粗细度的管理————毕竟,不同字体的管理本质上也和单一字体的不同粗细度管理差不多,可以融会贯通。
规范介绍
通常,需要在 src 的 assets 的 style 下统一引入 font 文件,并进行声明,这样在后续的业务中进行使用,就可以直接使用 css 来进行使用了。
接下来将会介绍如何在 style 中配置引入的 font 文件,以及如何在业务中进行使用。
常规管理方案
通过配置统一的 font-family 和使用 font-weight 进行区分,可以在多数情况下满足需求:
// 配置
@font-face {
font-family: "Custom";
font-style: normal;
font-weight: 400;
src: url("../fonts/1.ttf");
font-display: swap;
}
@font-face {
font-family: "Custom";
font-style: normal;
font-weight: 500;
src: url("../fonts/2.ttf");
font-display: swap;
}
@font-face {
font-family: "Custom";
font-style: normal;
font-weight: 600;
src: url("../fonts/3.ttf");
font-display: swap;
}
// 业务用法
.example {
font-family: "Custom";
font-weight: 400; // 即可匹配到对应字体对应粗细度的字体文件
}
不那么优雅的方案
分别设置不同的 font-family 为每种粗细定义不同的字体:
// 配置
@font-face {
font-family: "Custom";
font-style: normal;
font-weight: 400;
src: url("../fonts/1.ttf");
}
@font-face {
font-family: "Custom_medium";
font-weight: 400;
src: url("../fonts/2.ttf");
}
@font-face {
font-family: "Custom_bold";
font-style: normal;
font-weight: 400;
src: url("../fonts/3.ttf");
}
// 业务使用
.example {
font-familt: "Custom_bold"; // 自动匹配了bold的字体
}
移动端特有的解决方案
考虑到 Android 和 iOS 的字体渲染差异,可能需要为每个平台指定不同的字体或样式。
// 字体配置示例
export const FONT_FAMILY = Platform.select({
android: { fontFamily: "Custom-Regular" },
ios: {},
});
export enum CustomFont {
Light = "Custom-Light",
Regular = "custom_regular",
Medium = "custom_medium",
Bold = "Custom-Bold",
}
export type FontStyle =
| {
fontWeight: "300" | "400" | "600" | "700";
}
| {
fontFamily: CustomFont;
};
export const FONT_LIGHT: FontStyle = Platform.select({
ios: {
fontWeight: "300",
},
android: {
fontFamily: CustomFont.Light,
},
});
export const FONT_REGULAR: FontStyle = Platform.select({
ios: {
fontWeight: "400",
},
android: {
fontFamily: CustomFont.Regular,
},
});
结语
本文主要讲了如何进行 font 的管理,以及对应业务中的使用,主要是对单一字体不同粗细度的管理,其实本质上还是对不同字体的管理。
难度很低,主要是一种规范的记录,如果之前没有对字体做过特殊处理的规范的话,还是有必要学习一下的,我个人推荐第一种方式,业务中也好理解,代码也会更好维护一点。
COMMENTS · 0
还没有公开评论。