说明
分享一个dart脚本,用于将iconfont的在线css链接,自动下载里面的ttf文件到本地 和 自动格式化name和十六进制值。
/// iconfont 处理脚本
import 'dart:ffi';
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'dart:io';
String cssUrl = 'https://at.alicdn.com/t/c/font_4169331_7nid1mbh75g.css';
void main () async {
// 第一步:下载 css 文件
final res = await http.get(Uri.parse(cssUrl));
// 第二步:解析内容
final String contentText = utf8.decode(res.bodyBytes);
print(contentText);
// 第三步:获取ttf地址
RegExp ttfRegexp = RegExp(r"url\('([^']+\.ttf\?t=\d+)'\)");
Iterable<Match> ttfMatches = ttfRegexp.allMatches(contentText);
final String ttfUrl = 'https:${ttfMatches.first.group(1)!}';
print(ttfUrl);
// 第四步:下载ttf文件,并保存到当前目录里,命名为iconfont.ttf
final ttfRes = await http.get(Uri.parse(ttfUrl));
String dirPath = File(Platform.script.toFilePath()).parent.path;
var ttfFile = File('$dirPath/iconfont.ttf');
await ttfFile.writeAsBytes(ttfRes.bodyBytes);
// 第五步:解析css文件里的
RegExp regex = RegExp(r'\.(\w+):before[\s\S]*?content:\s*"\\([a-zA-Z0-9]+)');
Map<String, String> iconMap = {};
Iterable<Match> matches = regex.allMatches(contentText);
for (Match match in matches) {
String className = match.group(1)!;
String content = match.group(2)!;
iconMap[className] = '0x$content';
}
var mapFile = File('$dirPath/icon_map.dart');
String generateMapCode(Map<String, String> map) {
String mapEntries = map.entries.map((entry) => " '${entry.key}': ${entry.value},").join('\n');
return '''Map<String, int> iconMap = {
$mapEntries
};
''';
}
String mapFileContent = generateMapCode(iconMap);
mapFile.writeAsStringSync(mapFileContent);
}
icon_map.dart里面只放了一个map对象,供index组件使用
自定义字体 iconfont 设置颜色无效
我使用iconfont里的ttf字体时,总是设置颜色无效
最后发现是这两处需要修改一下
1、项目设置里把彩色取消掉
2、批量操作 - 全选 - 批量去色
总结
1、该脚本大部分代码都是chatGPT写的,比如正则、自动构建dart文件,不得不感慨gpt实在太强了,在学习一门新语言时,他就好像一个导师一样,不管你问什么问题他都会解答,比加什么学习群都高效和答案更精准。