使用方法
在 pubspec.yaml 中的 flutter 下添加以下信息
...
flutter:
fonts:
- family: IconFont
fonts:
- asset: iconfont/iconfont.ttf
...
Flutter 中使用:
import 'iconfont.dart';
// 其中 xxx,为 iconfont 对应的名字,可以 Chrome 打开
// demo_fontclass.html 查看对应名称
new Icon(IconFont.xxx)
其中 iconfont.dart 文件可以通过程序转换而来。
我这里使用 Python,你可以使用任何你喜欢的语言做这个事情。
每次图标文件有变化时,运行一下这个脚本即可生成新的 dart 文件。需要注意,由于 ttf 为静态字体文件,有变化后,需要重新打包运行 APP,否则不会生效。
转换方法
在 iconfont.cn 选择好要使用的图标后,下载到本地。解压之后,将所有文件(.js、.ttf、*.css等所有文件)复制到项目根目录:
$ tree . -L 1
# 注意下面的 iconfont 与 ios/android/lib 等同级
.
├── analysis_options.yaml
├── android
├── build
├── iconfont *************** 放在这里 **************
├── ios
├── lib
├── pubspec.lock
├── pubspec.yaml
├── README.md
└── test
# 其中 iconfont 的目录结构如下:
$ tree iconfont -L 1
iconfont
├── demo.css
├── demo_fontclass.html
├── demo_symbol.html
├── demo_unicode.html
├── iconfont.css ************* 需要 ****************
├── iconfont.eot
├── iconfont.js
├── iconfont.svg
├── iconfont.ttf ************* 需要 ****************
└── iconfont.woff
其中需要用到 iconfont.ttf 和 iconfont.css 文件,其余的文件不需要。
但是最好全部保留在项目 git 中,因为在开发过程中需要随时查看图标对应的代码及预览。
预览时用 Chrome 打开 demo_fontclass.html 即可。
通过以下 Python 3 代码转换为 dart 文件:
# coding: u8
import re
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
MAIN = ROOT
# 将 iconfont 的 css 自动转换为 dart 代码
def translate():
print('Begin translate...')
code = """
import 'package:flutter/widgets.dart';
// 代码由程序自动生成。请不要对此文件做任何修改。
class IconFont {
IconFont._();
static const font_name = 'IconFont';
{icon_codes}
}
""".strip()
strings = []
tmp = []
p = re.compile(r'.icon-(.*?):.*?"\\(.*?)";')
content = open(MAIN / 'assets/iconfont/iconfont.css').read().replace('\n content', 'content')
for line in content.splitlines():
line = line.strip()
if line:
res = p.findall(line)
if res:
name, value = res[0]
name = name.replace('-', '_')
tmp.append((name.lower(), value))
tmp.sort()
for name, value in tmp:
string = f' static const IconData {name} = const IconData(0x{value}, fontFamily: font_name);'
strings.append(string)
strings = '\n'.join(strings)
code = code.replace('{icon_codes}', strings)
open(MAIN / 'lib/widgets/iconfont.dart', 'w').write(code)
print('Finish translate...')
if __name__ == "__main__":
translate()
使用方法:
比如将转换文件放到项目根目录:
$ python3 ./translate_icon_font_from_css_to_dart.py
将在 lib 目录下生成 iconfont.dart 文件。