版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
一般reactnative有个react-native-vector-icons的图标库依赖包,里面集成各种图标字体,如果想做自定义的图标,也是需要安装这个依赖包
react-native-vector-icons的使用
// 安装依赖包
npm install --save react-native-vector-icons
// 链接原生库(这个很重要,链接完,android\app\src\main\assets 安卓里的main就会多个一个字体包)
react-native link react-native-vector-icons
// 使用
import Icon from "react-native-vector-icons/Ionicons";
<Icon name='md-pricetag' size={16} color='#cccccc'></Icon>
查看各个图标库的图标:https://www.npmjs.com/package/react-native-vector-icons
自定义图标
设置自定义图标前,也是要在上面的步骤的基础上完成
1、阿里图库下载图标
2、把下载包里的 iconfont.ttf 复制到 android\app\src\main\assets\fonts 里面
3、新建组件myicon/index.js
// index.js
import createIconSet from 'react-native-vector-icons/lib/create-icon-set';
import glyphMap from './iconfont.json';
const iconSet = createIconSet(glyphMap, 'myIcon', 'iconfont.ttf');
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;
4、生成iconfont.json配置文件
参考:https://www.jianshu.com/p/c142dd7df621
另起文件夹新建 buildJson.js,把阿里图库下载的svg复制进来,node buildJson.js 运行,可以快速生成json配置文件
// buildJson.js
const fs = require('fs');
const path = require('path');
const lineReader = require('readline').createInterface({
input: require('fs').createReadStream(path.join(__dirname,'./iconfont.svg'))
});
const names = [];
console.log('create...');
lineReader.on('line', function (line) {
let words = line.split(' ');
if(words[4]==='<glyph'){
let [key,value] = [words[5].slice(12,-1),words[6].slice(11,-2)];
if(value){
names.push(' "'+key+'":'+value);
}
}
});
lineReader.on('close',function () {
return fs.writeFile(path.resolve(__dirname, './iconfont.json'), '{\n'+names.join(',\n')+'\n}', function (err) {
if (err) {
throw new Error(err)
} else {
console.log('create successe.');
}
})
});
生成后为
// iconfont.json
{
"shoucang":58950,
"shouye":58921,
"buoumaotubiao45":58929,
"dianying":59001,
"wode":58918
}
再把文件复制到myicon组件里
5、使用
import Myicon from "../component/myicon";
<Myicon name='dianying' size={36} color='#cccccc'></Myicon>