阅读 804

expo 下react native 使用 iconfont 自定义图标笔录

效果图展示

步骤如下

  1. www.iconfont.cn 内下载个人iconfont.zip 目录内容为:

  1. 利用脚本 setting.sh 文件调整 iconfont.json 文件格式
提取 iconfont.json 的 name 值和 unicode_decimal 值组成新的键值对 json文件,
与 expo createIconSet 期望格式达成一致
复制代码

在 iconfont.zip 解压文件夹下添加 setting.sh 文件,添加如下:

#!/bin/sh

if [ $# != 1 ] ; then

    echo "usage: $0 iconfont.svg(iconfont.svg)  "
    exit
fi

#OutputFile path,you can customize your path
OutputFileName=`echo iconfont.json`

mapper=` awk '{ if($0 ~ /glyph-name/) print $0;  if($0 ~ /unicode/)  print $0"|split|" }'  $1| tr '[:upper:]' '[:lower:]'| awk '{print $0}'  RS='\='| tr "\n\"&#;" " "| awk  '{ if ($1!="split"&&$1!=""){ printf ("\""$3"\":"); printf ($5","); print "\r " }}' RS="|split|" | sed "s/-/_/g"`

rm $OutputFileName
echo "{" >> $OutputFileName
echo $mapper >> $OutputFileName
echo "}" >> $OutputFileName

#usage:
# ./iconfont_mapper.sh svg_file_path

复制代码

保存退出并在当前目录下执行 ./setting.sh iconfont.json

(若遇权限问题,可先执行 chmod 777 setting.sh )

成功后 iconfont.json 文件内容格式改变

修改前格式:
{
  "id": "1265309",
  "name": "diary",
  "font_family": "iconfont",
  "css_prefix_text": "icon-",
  "description": "",
  "glyphs": [
    {
      "icon_id": "58330",
      "name": "delete",
      "font_class": "delete",
      "unicode": "e621",
      "unicode_decimal": 58913
    },
    ...
    ]
}
复制代码
修改后格式:
{
 "delete":58913,
 "mobile":59140,
 "to_left":58880,
 "to_right":58881,
 "hourglass":58960,
 "upload":59004,
 "sey_write_a":58988,
 "feedback":59003,
 "delete1":58888,
 "refresh":59345,
 "praise":59077,
  ...
 }

复制代码
  1. 文件保存到项目目录内备用
iconfont.tff文件:iconfont.zip 解压后的文件夹内
iconfont.json:上一步骤中生成的新格式文件
比如放入项目根目录下的 assets/fonts/ 文件夹内
复制代码
  1. npm install --save react-native-vector-icons

    node_modules/@expo/...内会加入 create-icon-set.js 文件
    复制代码
  2. 新建组件Icon.js

// 根据个人 create-icon-set.js 文件路径引入
import createIconSet from "@expo/vector-icons/build/vendor/react-native-vector-icons/lib/create-icon-set.js";
import glyphMap from "../assets/fonts/iconfont.json";

const iconSet = createIconSet(
  glyphMap,
  "MixIcon",
  "../assets/fonts/iconfont.ttf"
);

export default iconSet;
复制代码
  1. 项目App.js初始页面预加载 iconfont.ttf 文件
import * as Font from "expo-font";

export default function App(props) {

    // 根据个人情况在适当位置调用该方法,如 componentDidMount() 内
    function loadResourcesAsync() {
        Font.loadAsync({
          MixIcon: require("./assets/fonts/iconfont.ttf")
        })
    }
    
}
复制代码
  1. 页面使用
import MixIcon from "../../components/Icon";
   
   ...
   
<MixIcon name="mobile" size={24} color="#226688" />
<MixIcon name="refresh" size={24} color="#226688" />
<MixIcon name="praise" size={24} color="#226688" />
<MixIcon name="homemin" size={24} color="#226688" />

复制代码

(END)

文章分类
代码人生
文章标签