uni-app 应用等宽字体对齐数字宽度
0️ 问题 ❓
开发的过程中遇到数字显示列表,发现同样的数字数宽度不一。android 不会有, web 浏览器和 ios 会呈现。
之前也有遇到过,也解决了,写过文章记录 在网站中应用谷歌“ROBOTO”字体(解决 ios 数字 1 和 0 大小不等宽问题),不过文章没有明确的代码,也比拟潦草,这次加上代码。
本次解决方案不仅仅实用于 uni-app,包含 nvue, 还有一般的 vue react 我的项目都能用。晓得原理了,移植解决方案很简略。
起因:默认或者应用了非等宽字体,安卓默认的字体 Roboto 就是等宽的,啥叫非等宽,就是字体的宽度不一样,比方 1
和 2
在显示的时候所占用的宽度不一样。(中文字体默认就是等宽的)
<img src="https://image.yoouu.cn/2021/dev-diary01/img1.jpg" style="zoom: 50%;" />
解决后:
看起来难受了很多 ????
<img src="https://image.yoouu.cn/2021/dev-diary01/img2.jpg" style="zoom: 50%;" />
1️ 下载须要的字体
链接:https://www.fontsquirrel.com/fonts/roboto
- 抉择
Webfont Kit
- Choose a Subset 默认就行
- Choose Font Formats 默认的 WOFF就行
- 点击 Download @font-face Kit
- 关上压缩包应用 roboto_regular_macroman/Roboto-Regular-webfont.woff
2️ 在 uni-app 中应用
本次测试了 app,h5 端,其余端未测试,实践通用。
将下载的 Roboto-Regular-webfont.woff 放在 我的项目的 static/fonts/Roboto-Regular-webfont.woff
新建 ${app}/common/scss/font.scss
${app}
指代我的项目。
@font-face { font-family: 'robotoregular'; src: url('/static/fonts/Roboto-Regular-webfont.woff') format('woff'); font-weight: normal; font-style: normal;}
新建 ${app}/common/sass/index.scss
@import 'font.scss';
在 ${app}/App.vue
中导入
<style lang="scss"> /* #ifndef APP-NVUE */ page { font-family: robotoregular, PingFang SC, Hiragino Sans GB, Heiti SC, Microsoft YaHei, WenQuanYi Micro Hei, Helvetica, Arial, monospace, serif; } /* #endif */</style>
ok,功败垂成。非 nvue 的页面如果没自定义 font-family
的字体应该曾经失效了。
3️ 在 nvue 页面中应用
nvue
渲染逻辑不同于 webview
所以这种形式在 nvue
是不失效的。精确来说,你在 nvue
中这么用会报错 ????。
nvue
的字体加载文档:https://weex.apache.org/zh/docs/modules/dom.html#addrule
具体的细节不多说了,间接上逻辑和代码,在尝试了各种形式后,最终决定在须要应用等宽字体的 text
组件上封装组件。这样耦合小,保护啥的不便点。
转换字体文件到 base64
首先咱们须要用这个 https://www.giftofspeed.com/base64-encoder/ 网址把咱们的字体文件转换成 base64
编码,因为导入字体文件,门路啥的在 nvue
不是很好解决。
新建 ${app}/components-nvue/c-roboto-font/c-roboto-font.vue
最好不要动格局,否则你会发现会多出一些空格换行啥的 ????。新建 nvue 专用的文件夹。以
c
结尾方便使用easycom
, 当然你能够自定义。
<template><text class="roboto-font">{{ text }}</text></template><script> export default { props: { text: { type: String, required: true, }, }, beforeCreate() { const dom = uni.requireNativePlugin('dom') dom.addRule('fontFace', { fontFamily: 'robotoregular', src: "url('data:font/truetype;charset=utf-8;base64,[这里填写你的字体文件转换进去的base64编码,别写错了]')", }) }, }</script><style scoped> .roboto-font { font-family: robotoregular; }</style>
配置 easycom
${app}/pages.json
{ "easycom": { "^c-(.*)": "@/components-nvue/c-$1/c-$1.vue" }}
应用
<c-roboto-font :text="foo.count" />
???? 开发日记系列
只记录些平时开发感觉有用的货色,有问题请务必斧正,托付了 ????????????
- 开发日记 01-uni-app 应用等宽字体对其数字显示
对于我
SunSeekerX,前端开发、Nodejs 开发、小程序、uni-app
开发、等等
喜爱探讨技术实现计划和细节,完满主义者,见不得bug
。
Github:https://github.com/SunSeekerX
集体博客:https://yoouu.cn/
集体在线笔记:https://doc.yoouu.cn/