react-native 使用第三方字體圖標(biāo)庫(kù)-阿里字體圖標(biāo)庫(kù)

一、安裝react-native-vector-icons可自定義icon的依賴

1: yarn add react-native-vector-icons
2: cd ios
3: pod install
4: cd ..

二、下載阿里字體圖標(biāo)包

下載阿里字體圖標(biāo)包

三、拷貝字體文件

字體文件

android

android將字體文件拷貝到/rntstest/android/app/src/main/assets/fonts/(rntstest項(xiàng)目名稱)下,如果沒有fonts,可以自己建一個(gè)文件夾。如圖下圖


android字體存放目錄

ios

ios 導(dǎo)入字體文件


xcode導(dǎo)入字體

可以選擇項(xiàng)目?jī)?nèi)字體文件或者選擇Add Other選擇非xx.xcworkspace下的字體文件


選擇字體文件

選擇字體文件

選擇字體文件

info.list添加字體


info.list添加字體

info.list添加字體

四、自定義Iconfont組件存放目錄隨意,我這里放在assets/font/

assets/font/目錄

將字體包c(diǎn)ss拷貝至font目錄下


將字體包c(diǎn)ss拷貝至font目錄下

新建一個(gè)生成iconfont.json的腳本命令


新建一個(gè)生成iconfont.json的腳本命令

腳本代碼
const path = require('path');
const fs = require('fs');
const css = require('css');
const filePath = path.join(__dirname, '../assets/font/iconfont.css');
const fileStr = fs.readFileSync(filePath);
const obj = css.parse(fileStr.toString());
const outputJson = {};
obj.stylesheet.rules.forEach(val => {
  try {
    //注意如果沒有自定義圖標(biāo)名稱請(qǐng)使用 if (val.selectors[0].indexOf('.icon-') !== -1) {
    if (val.selectors[0].indexOf('.TRP-') !== -1) {
      let key = val.selectors[0].replace('.', '').replace(':before', '');
      let base16 = val.declarations[0].value
        .replace(/\\/g, '')
        .replace(/\"/g, '');
      outputJson[key] = parseInt(base16, 16);
    }
  } catch (e) {}
});
// const outPut = `export default ${JSON.stringify(outputJson, null, 2)}`;
const outPut = JSON.stringify(outputJson, null, 2);
fs.writeFile(
  path.join(__dirname, '../assets/font/iconfont.json'),
  outPut,
  err => {
    if (err) throw err;
    console.log('寫入成功!');
  },
);

// package
{
"name": "rntstest",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "android": "react-native run-android",
    "ios": "react-native run-ios",
    "start": "react-native start",
    "test": "jest",
    "lint": "eslint . --ext .js,.jsx,.ts,.tsx",
    "postinstall": "patch-package",
    "build:iconfont": "node ./scripts/iconfont2json.js"
  },
}

執(zhí)行npm run build:iconfont生成iconfont.json
在font/下新建一個(gè)index.js

import {createIconSet} from 'react-native-vector-icons'
const fontJson = require('./iconfont.json');
export const Iconfont = createIconSet(fontJson, 'trp-font', 'iconfont.ttf');

使用

import React from 'react';
import {
    SafeAreaView,
    ScrollView,
    Text,
    View,
    Image,
    StatusBar,
    useColorScheme,
    Button,
    StyleSheet,
    Dimensions
} from 'react-native'
// 導(dǎo)入組件
import {Iconfont} from "../../assets/font";
import {Colors} from "react-native/Libraries/NewAppScreen";

const windowWidth = Dimensions.get('window').width;
const windowHeight = Dimensions.get('window').height;
const styles: any = StyleSheet.create({
    containerWidth: {
        width: windowWidth,
        height: windowHeight
    }
})
const Home = ({route, navigation}) => {
    const isDarkMode = useColorScheme() === 'dark';
    const backgroundStyle = {
        backgroundColor: isDarkMode ? Colors.darker : Colors.lighter,
    };
    const linkTo = (target: String) => navigation.navigate(target, {
        id: 1000,
        otherParams: 'anything you want here'
    });
    return (
        <SafeAreaView style={{flex: 1, backgroundColor: '#fff'}}>
            <StatusBar barStyle={isDarkMode ? 'light-content' : 'dark-content'}/>
            <ScrollView>
                <View>
                    <Text style={{textAlign: 'center'}}>list</Text>
                    <Image source={require('../../assets/img/MV.jpeg')} style={styles.containerWidth}
                           resizeMode={'cover'}/>
                    // 使用組件name為字體圖標(biāo)名稱,size設(shè)置大小,color設(shè)置圖標(biāo)顏色
                    <Iconfont name={'TRP-Star'} size={54} color={'#9feb42'}/>
                    <Button title={'查看詳情'} onPress={() => {
                        linkTo('Detail')
                    }}/>
                </View>
            </ScrollView>
        </SafeAreaView>
    )
};
export default Home

執(zhí)行npm run ios/npm run android查看效果


ios
android

版本說(shuō)明
"react-native": "0.64.0",
"react-native-vector-icons": "^8.1.0",

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容