在react-native-vector-icons中使用自定義圖標

react-native-vector-icons的安裝參考鏈接

這裏主要介紹如何在react-native-vector-icons中使用iconfont官網
上的圖標。

1、下載圖標素材

首先在iconfont網站上挑選好圖標,或者自己的設計將圖標上傳上去之後,加入購物車,

在這裏插入圖片描述
選好所有的圖標後, 在購物車選擇下載代碼。解壓後得到如下文件
在這裏插入圖片描述
這裏我們只需要iconfont.tff文件和iconfont.json文件。

2、將圖標字體添加到項目中

主要分三步(node_modules -> react-native-vector-icons目錄下):

  1. 將下載的TTF文件copy到Fonts文件夾下。
  2. glyphmaps創建自定義的Json文件。
  3. react-native-vector-icons目錄下創建js文件。

1、首先將下載好的iconfont.ttf文件copy到react-native-vector-icons->Fonts文件夾下並改名爲 MyFont.ttf

2、在glyphmaps文件夾下創建 MyFont.json 文件,內容如下

{
  "name1": 58958,
  "name2": 58959,
  "name3": 58960
}

PS: 其中的name1、name2、name3爲引用時的圖標名稱可以自定義,value值從iconfont.json中獲取。如圖:
在這裏插入圖片描述
unicode_decimal 字段對應的值作爲json文件中的value值。

3、在react-native-vector-icons文件夾下創建MyFont.js文件,仿照自帶的js文件寫法輸出一個控件如下,

import createIconSet from './lib/create-icon-set';
import glyphMap from './glyphmaps/MyFont.json';

//第一個參數爲json文件 第二個參數爲font_family 第三個爲字體文件
const MyFont = createIconSet(glyphMap, 'iconfont', 'MyFont.ttf');

//輸出字體圖標控件
export default MyFont;

export const Button = MyFont.Button;
export const TabBarItem = MyFont.TabBarItem;
export const TabBarItemIOS = MyFont.TabBarItemIOS;
export const ToolbarAndroid = MyFont.ToolbarAndroid;
export const getImageSource = MyFont.getImageSource;

PS: 這裏用到了剛纔創建的ttf文件和json文件。輸出MyFont控件可以在代碼中使用。

3、在Xcode中鏈接字體文件

打開iOS項目,將MyFont.ttf文件引入到項目中。
在項目文件夾上右鍵選擇add files to XXX ,只需要添加引用就行了,勾選creat folder refrences
在這裏插入圖片描述
target -> build phases -> copy bundle resources 中點加號Myfont.ttf 文件加入。
target->info->Fonts provided by application 中添加字體如下
在這裏插入圖片描述

4、在代碼中中使用

import MyFont from 'react-native-vector-icons/MyFont'
<MyFont name={'name1'} size={50} color={'red'} />
<MyFont name={'name2'} size={50} color={'black'} />
<MyFont name={'name3'} size={50} color={'blue'} />

在這裏插入圖片描述

5、一個方便的第三方

使用react-native-vector-icons每次都需要將自己文件打包到項目中,推薦使用第三方鏈接來進行動態集成。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章