React Native 开发豆瓣评分(六)添加字体图标

添加依赖

yarn add react-native-vector-icons
react-native link react-native-vector-icons

使用默认字体图标

import Icon from 'react-native-vector-icons/AntDesign'; //可以选择AntDesign、FontAwesome、EvilIcons...

<Icon name="search1" size={30} color="#900" />
<Icon.Button name="search1" onPress={() => alert(666)}>
    Login with Facebook
</Icon.Button>

使用自定义字体图标

  1. android\app\src\main\assets\fonts 目录下 添加 .ttf 文件(test.ttf);

  2. 在 components 目录下创建自定义 Icon 组件(icon.js):

    import createIconSet from 'react-native-vector-icons/lib/create-icon-set';
    const glyphMap = {"yinle":58880,"chongbangx":58881};
    //yinle 为即将使用的name的值,58880 为 ttf 图标对应的 16 进制值
    const Icon = createIconSet(glyphMap, 'test', 'test.ttf');
    export default Icon;
    
  3. 使用自定义 Icon 组件:

    import Icon from '../components/icon';
    ...
    <Icon name='yinle' size={38} onPress={() => alert('自定义Icon')} />
    ...
    
  4. 获得 .ttf 文件的 name 与 16 进制字符串:

    • 在命令行依次执行以下步骤

      mkdir transfromttf
      cd transfromttf
      npm init -y
      touch index.js
      npm install font-carrier --save
      
    • 编辑 index.js

      var fontCarrier = require('font-carrier')
      var fonts = fontCarrier.transfer('./iconfont.ttf').__glyphs;
      
      var obj = {};
      for(let key in fonts){
          obj[fonts[key].options.name] = parseInt(fonts[key].options.unicode.replace('&#x',''),16);
      }
      console.log(JSON.stringify(obj))
      
    • 将 .ttf 文件复制到 transfromttf 目录,运行 index.js 即可得到 glyphMap

      node index.js
      

减少 apk 包体积

react-native-vector-icons 自带 16 种字体文件,可参考:react-native-vector-icons,并非每一种风格的字体图标我们都会使用,甚至我们只会使用 ui 给我们的 .ttf 文件,所以为了 apk 大小考虑,可以删除 android\app\src\main\assets\fonts 目录下未使用的 .ttf 文件,全部删除的话,apk 大概减少1M 多。

posted @ 2019-07-04 16:58  啤酒煮鸡蛋  阅读(260)  评论(0编辑  收藏  举报