优缺点
优点:不需要占用本地存储,可直接在线同步库图标,不用再手动引入ttf文件,不用手动添加键值对对应表。
缺点:受网速影响,字体库cdn路径可能会更改,ios端首次加载,可能会无图标(详见: ios无授权请求不了网络)。
开发可用线上修改,生产用本地文件。
1.通过css url获取获取唯一标识对应的ttf文件
这里使用的是codesign的示例,阿里巴巴矢量图同理
uni.request<String>({
// css路径,即最初提供的路径
url: "https://cdn2.codesign.qq.com/icons/5OjE7NgEbM8mM03/latest/iconfont.css",
success: (res : RequestSuccess<string>) => {
// 会将内容以文本返回
this.extractCssContent(res.data!)
// codesign的唯一标识是t,根据正则或者字符串处理方法,求得t标识的值
const match = res.data!.toString().match(/url\('.*?[\?&]t=([^&']*)/)! as String[];
uni.loadFontFace({
global: true,//应用到全局
family: 'LYIcon',//自定义字体名称
// 求得的值的下标为1
source: `https://cdn2.codesign.qq.com/icons/5OjE7NgEbM8mM03/latest/iconfont.ttf?t=${match[1]}`,
})
}
})
css解析 为键值对
function extractCssContent(cssText : string) {
// 解析为{ name:'e001' }样式的键值对
let icons = cssText.split('.icon-').slice(1).reduce((prev : UTSJSONObject, i : string) : UTSJSONObject => {
let key = (i.split(':') as string[])[0];
let val = ((((i.split('content:') as string[])[1].split(';') as string[])[0]).split('\\') as string[])[1].slice(0, -1);
prev.set(key, val)
return prev
}, {} as UTSJSONObject);
ConfigStore.setIcons(icons);
}
2.解析后的文件使用
计算Unicode码
// 映射表
const reflect = {
'play-custom': 'play'
};
const calcText = (key : string) : String => String.fromCharCode(parseInt('e001')!, 16))
// 解析字符串 icons是存储的对象 为防止重名冲突,reflect为映射表 parseInt解析16位字符为10进制
const calcText = (key : string) : String => String.fromCharCode(parseInt(icons.value.getString(key in reflect ? reflect.getString(key)! : key)!, 16))
使用
<text>{{calcText('play-custom')}}</text>