dixylo
dixylo

Reputation: 68

How do you use a customized font with a single file for android in react native?

I added a customized font to my react native project. The font only has a single ttf file (e.g. FontFamilyName.ttf), instead of multiple files for each style (e.g. FontFamilyName-Regular.ttf, FontFamilyName-Bold.ttf, FontFamilyName-SemiBold.ttf, FontFamilyName-Thin.ttf). But it is a font collection that contains multiple styles like Bold, Thin, SemiBold, etc. I can see all the variants with the Mac App FontBook.

For iOS, I can successfully use every style of the font by specifying "fontFamily" with the postscript name of each style (e.g. FontFamilyName-Thin). But for Android, I can only use the default style - "regular" by specifying "fontFamily" with the name of the ttf file (i.e. FontFamilyName). I can't find a way to use other styles. Specifying "fontFamily" with the postscript name of a style like I do for iOS doesn't work for Android.

Upvotes: 2

Views: 1199

Answers (2)

dixylo
dixylo

Reputation: 68

For those who have the same problem using variable fonts, which are single-filed, currently the best solution I've found is to use an app called 'Slice' to slice the font variations from the single file and add the separate font files to your project.

For how to use Slice, check out https://medium.com/timeless/adding-custom-variable-fonts-in-react-native-47e0d062bcfc

For how to add custom fonts to your project, check out https://mehrankhandev.medium.com/ultimate-guide-to-use-custom-fonts-in-react-native-77fcdf859cf4

Upvotes: 0

mainak
mainak

Reputation: 2311

  1. Create a new directory called "fonts" in the "assets" directory of your React Native project.

  2. Copy the custom font file (e.g. TTF or OTF file) into the "fonts" directory.

  3. In your React Native app's "android/app/build.gradle" file, add the following line to the "android" section:

    assets.srcDirs = ['assets/fonts']

  4. In your React Native app's "android/app/src/main/res/values/styles.xml" file, add the following line to the "resources" section:

style name="CustomFont" parent="android:TextAppearance.Material.Body1"> item name="android:fontFamily">@font/YOUR_CUSTOM_FONT_NAME /item> /style>

  1. In your JS code, you can apply the custom font to a specific text by adding the fontFamily style, like so:

    <Text style={{ fontFamily: 'CustomFont' }}>Hello World

  2. Lastly, rebuild your app using "react-native run-android" command. Note: If you have multiple custom fonts, you will need to repeat step 4 for each font, using a different style name each time.

ps: for point 4. style code need to remove < before style tag and item tag as stackoverflow was discarding the text in the comments

Upvotes: 0

Related Questions