728x90
728x90

커스텀 폰트 사용하기 (expo-font)

들어가며

  • 리액트 네이티브(React Native) 엑스포(Expo) 프로젝트에서 커스텀 폰트를 적용하는 방법을 간단하게 정리해본다.

 

방법

1️⃣ 패키지 설치하기

  • 폰트 사용을 위해 expo-font 패키지를 설치한다.
$ expo install expo-font
expo install 명령은 현재 Expo 프로젝트의 버전과 호환되는 패키지를 자동으로 설치해준다.

 

 

2️⃣ 폰트 파일 준비하기

  • 프로젝트의 /assets/fonts 폴더 안에, 추가할 커스텀 폰트 파일을 넣어준다.
    • 해당 폴더가 없을 경우, 새로 생성해준다.

assets/fonts 폴더에 폰트 파일을 넣은 모습

 

4️⃣ 폰트 불러오기 (useFonts 훅)

  • 프로젝트 최상단에 있는 App.js 파일에 다음과 같은 커스텀 폰트를 불러오는 코드를 추가해준다.
  • useFont 훅을 사용하여 폰트를 불러와줄 수 있다.

 

/App.js
import { useFonts } from 'expo-font';
export default function App() {
const [fontsLoaded] = useFonts({
'open-sans': require('./assets/fonts/OpenSans-Regular.ttf'),
'open-sans-bold': require('./assets/fonts/OpenSans-Bold.ttf'),
});
// ...
}

 

  • 차후에 useFont 내부의 객체의 키(Key)를 이용하여 특정 요소에 폰트를 적용시킬 것이다. (open-sans, open-sans-bold)
  • require 메서드를 이용하여 폰트가 저장된 경로를 추가해준다.

 

5️⃣ 폰트 로딩 중 로딩 화면 표시해주기 (선택)

  • 폰트가 로드되기 전까지 시간이 걸릴 수 있는데, 이때 다음과 같이 간단한 라이브러리를 이용하여 로딩중 화면을 표시해줄 수 있다.
$ expo install expo-app-loading

 

/App.js
import { useFonts } from 'expo-font';
import AppLoading from 'expo-app-loading'; // 추가
export default function App() {
const [fontsLoaded] = useFonts({
'open-sans': require('./assets/fonts/OpenSans-Regular.ttf'),
'open-sans-bold': require('./assets/fonts/OpenSans-Bold.ttf'),
});
// 로딩중 화면 표시
if (!fontsLoaded) {
return <AppLoading />;
}
// ...
}

 

6️⃣ 폰트 사용하기

  • 이제 각 컴포넌트 스타일에 fontFamily를 지정하여 커스텀 폰트를 사용할 수 있다.

 

/components/NumberContainer.js
import { View, Text, StyleSheet } from 'react-native';
import Colors from '../../constants/colors';
function NumberContainer({ children }) {
return (
<View>
<Text style={styles.numberText}>{children}</Text>
</View>
);
}
export default NumberContainer;
const styles = StyleSheet.create({
numberText: {
color: Colors.accent500,
fontSize: 36,
fontFamily: 'open-sans-bold', // 커스텀 폰트 사용하기
},
});

 

참고 사이트

 

Font

A library that allows loading fonts at runtime and using them in React Native components.

docs.expo.dev

 

expo-app-loading

A React component that keeps the native splash screen visible.. Latest version: 2.1.1, last published: 2 years ago. Start using expo-app-loading in your project by running n±iexpo-app-loadg. There are 71 other projects in the npm registry using expo

www.npmjs.com

728x90
728x90

커스텀 폰트 사용하기 (expo-font)들어가며방법1️⃣ 패키지 설치하기2️⃣ 폰트 파일 준비하기4️⃣ 폰트 불러오기 (useFonts 훅)5️⃣ 폰트 로딩 중 로딩 화면 표시해주기 (선택)6️⃣ 폰트 사용하기참고 사이트