1. 安装react-native-vector-icons
yarn add react-native-vector-icons react-native link
如果没有关联成功的话,可以参考官方文档手动配置一下
2. 将从阿里下载的iconfont.tff文件复制到以下目录
3. 在android/app/build.gradle
中添加:
project.ext.vectoricons = [
iconFontNames: ['iconfont.ttf' ] //添加你需要赋值的字符文件
]
apply from: "../../node_modules/react-native-vector-icons/fonts.gradle"
4. 在项目中创建字体配置文件
// DIYIcon.js
import createIconSet from 'react-native-vector-icons/lib/create-icon-set';
import glyphMap from './iconfont.json';
const iconSet = createIconSet(glyphMap, 'DIYIcon', 'iconfont.ttf'); // 'DIYIcon'可自定义名称
export default iconSet;
export const Button = iconSet.Button;
export const TabBarItem = iconSet.TabBarItem;
export const TabBarItemIOS = iconSet.TabBarItemIOS;
export const ToolbarAndroid = iconSet.ToolbarAndroid;
export const getImageSource = iconSet.getImageSource;
// iconfont.json
{
"glass": 61440,
"music": 61441,
"search": 61442,
"envelope-o": 61443,
"heart": 61444,
"star": 61445,
"star-o": 61446,
"user": 61447,
//等等...
}
附iconfont.json自动提取的方法:
4.1 安装python
点击下载pthon安装包https://www.python.org/ftp/python/2.7.14/python-2.7.14.msi
等待安装完成!
4.2 配置python环境变量
在path中添加 python安装目录以及Scripts
![](http://upload-images.jianshu.io/upload_images/1967155-914646bd8c412134.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/204/format/webp)
4.3 安装 fonttools
pip install fonttools
具体介绍请参考:github地址
4.4 准备react-native-iconfont-mapper
直接打包下载react-native-iconfont-mapper,或者通过git克隆到本地,这个目录自己选个容易记住的,因为以后用的比较多。
![](http://upload-images.jianshu.io/upload_images/1967155-1be06ab4dea5b46b.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/658/format/webp)
项目比较单一,仅仅一个python文件。
4.5 提取字符表
将前面下载的字体包中的ttf文件拷贝到这里
![](http://upload-images.jianshu.io/upload_images/1967155-b799b8c9074ce32e.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/672/format/webp)
python iconfont-mapper.py iconfont.ttf iconfont.js
![](http://upload-images.jianshu.io/upload_images/1967155-9d13e98ccb67af9d.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/651/format/webp)
不出意外,可以生成一个iconfont.js文件,打开查看便可以看到我们所需要的json字符串
![](http://upload-images.jianshu.io/upload_images/1967155-eda9a4d361349026.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1000/format/webp)
4.6 新建iconfont.json
{ "home": 58880, "setting": 58881, "code": 58886, "money": 58951, "phone": 58952, "user": 58890, "customer": 58993, "message": 59034, "add": 59418, "password": 58910 }
这里需要注意,刚才生成的字符表json对象后面的值有引号,这里需要删除
5. 使用
import DIYIcon from './diyicon/DIYIcon';
...
<DIYIcon name={'glass'} size={'50'} color={'#ed4040'} />
参考:
http://www.imbeta.cn/zai-react-nativezhong-you-ya-de-shi-yong-iconfont.html
https://segmentfault.com/a/1190000009939727
https://www.jianshu.com/p/332198bf46a7