react-native icon indicating copy to clipboard operation
react-native copied to clipboard

Using custom fonts in react-native project

Open samuelcouch opened this issue 11 years ago • 74 comments

Looking to add custom fonts to my react-native app -- can't seem to find any documentation on this.

samuelcouch avatar May 06 '15 04:05 samuelcouch

@samuelcouch - same as how you would in a regular iOS app :smile:

Follow steps 1-4 here: http://codewithchris.com/common-mistakes-with-adding-custom-fonts-to-your-ios-app/

Then you can use that font family inside of your styles

brentvatne avatar May 06 '15 04:05 brentvatne

Does RN support .woff fonts?

mixophrygian avatar Jun 12 '15 23:06 mixophrygian

I think it's restricted to what IOS allows.

I've used free TTF's in my react native project.

jaygarcia avatar Jun 13 '15 00:06 jaygarcia

Any tips on how to use custom fonts in Android?

satya164 avatar Sep 16 '15 09:09 satya164

@satya164 what have you tried? were you able to get anything working?

ccheever avatar Sep 17 '15 19:09 ccheever

@ccheever All examples on the web suggest to extend the default Android TextView. There is also one using reflection which changes the font for the whole app (this worked). Though this is acceptable, I would also prefer is to be able to declare font families and use them in styles, so that I can use icon fonts etc.

Here is the link if you you just want to change font family for entire app - http://stackoverflow.com/questions/2711858/is-it-possible-to-set-font-for-entire-application

NOTE: I used sans instead of monospace.

satya164 avatar Sep 17 '15 20:09 satya164

I had custom fonts working in a native Android app. Trying to port it over to RN now and they aren't loading inside of <Text> components :(

marcshilling avatar Sep 17 '15 21:09 marcshilling

@marcshilling can you describe in more detail what you tried? Do you still have .ttf files or similar in an assets/ folder? And how are you trying to use the custom fonts inside of RN? Just using the fontFamily style property on text nodes and referencing the fonts you are including?

ccheever avatar Sep 17 '15 21:09 ccheever

@ccheever yes, exactly. I've tried putting the .ttf (and .otf) files in both /assets and /assets/fonts (I had to the do the latter on native). And then I declare text like so:

<Text style={{fontFamily: 'FuturaStd-ExtraBold'}}>Hello World</Text>

And just for the record - I'm using the same exact font files and declaring <Text> the exact same way in an iOS React Native project and they are working.

marcshilling avatar Sep 17 '15 21:09 marcshilling

@marcshilling what do you mean with "I had to the do the latter on native", did you write "Typeface font = Typeface.createFromAsset" in the main activity?

geolivero avatar Sep 20 '15 01:09 geolivero

This is how I got custom font working,

  1. Put your font files under assets/fonts
  2. Add the following files

FontsOverride.java

import java.lang.reflect.Field;
import android.content.Context;
import android.graphics.Typeface;

public final class FontsOverride {
    public static void setDefaultFont(Context context,
                                      String staticTypefaceFieldName, String fontAssetName) {
        final Typeface regular = Typeface.createFromAsset(context.getAssets(),
                fontAssetName);
        replaceFont(staticTypefaceFieldName, regular);
    }

    protected static void replaceFont(String staticTypefaceFieldName,
                                      final Typeface newTypeface) {
        try {
            final Field staticField = Typeface.class
                    .getDeclaredField(staticTypefaceFieldName);
            staticField.setAccessible(true);
            staticField.set(null, newTypeface);
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }
}

MyApplication.java

import android.app.Application;

public class MyApplication extends Application {
    @Override
    public void onCreate() {
        super.onCreate();

        FontsOverride.setDefaultFont(this, "DEFAULT", "fonts/Custom-Font-Regular.ttf");
        FontsOverride.setDefaultFont(this, "SANS_SERIF", "fonts/Custom-Font-Regular.ttf");

        // You can also use "MONOSPACE" and "SERIF", but "DEFAULT" and "SANS_SERIF" is all you need
        FontsOverride.setDefaultFont(this, "MONOSPACE", "fonts/Custom-Font-Monospace.ttf");
        FontsOverride.setDefaultFont(this, "SERIF", "fonts/Custom-Font-Serif.ttf");
    }
}

res/values/styles.xml

<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
        ...
        <item name="android:typeface">sans</item>
    </style>

</resources>

Finally, in the <application> field of your AndroidManifest.xml, add the android:theme and android:name properties,

    <application
      ...
      android:name=".MyApplication"
      android:theme="@style/AppTheme"
      ...
      >

satya164 avatar Sep 20 '15 02:09 satya164

@satya164, you saved my day, i'm going going to try this tonight. Thanks! Geo

On Sun, Sep 20, 2015 at 4:36 AM, Satyajit Sahoo [email protected] wrote:

This is how I got custom font working,

  1. Put your font files under assets/fonts
  2. Add the following files

FontsOverride.java*

import java.lang.reflect.Field;import android.content.Context;import android.graphics.Typeface; public final class FontsOverride { public static void setDefaultFont(Context context, String staticTypefaceFieldName, String fontAssetName) { final Typeface regular = Typeface.createFromAsset(context.getAssets(), fontAssetName); replaceFont(staticTypefaceFieldName, regular); }

protected static void replaceFont(String staticTypefaceFieldName,
                                  final Typeface newTypeface) {
    try {
        final Field staticField = Typeface.class
                .getDeclaredField(staticTypefaceFieldName);
        staticField.setAccessible(true);
        staticField.set(null, newTypeface);
    } catch (NoSuchFieldException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    }
}

}

MyApplication.java

import android.app.Application;

public class MyApplication extends Application { @Override public void onCreate() { super.onCreate();

    FontsOverride.setDefaultFont(this, "DEFAULT", "fonts/Custom-Font.ttf");
    FontsOverride.setDefaultFont(this, "SANS_SERIF", "fonts/Custom-Font.ttf");
}

}

res/values/styles.xml

<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <item name="colorPrimary">@color/primary</item>
    <item name="colorPrimaryDark">@color/primary_dark</item>
    <item name="colorAccent">@color/accent</item>
    <item name="android:typeface">sans</item>
</style>

— Reply to this email directly or view it on GitHub https://github.com/facebook/react-native/issues/1167#issuecomment-141730183 .

Met vriendelijk groet, Gerald Olivero +31634771782 geolivero.com

geolivero avatar Sep 20 '15 12:09 geolivero

@geolivero No problem, I had left out the part where you have to change the AndroidManifest.xml, added it to the post now.

satya164 avatar Sep 20 '15 14:09 satya164

@satya164 what if I need multiple, different custom fonts in my app? You approach seems to simply replace the default font with a single custom font.

marcshilling avatar Sep 21 '15 18:09 marcshilling

@marcshilling Yeah, that will be immensely useful, e.g. - icon fonts. But I've not managed to figure that out yet.

satya164 avatar Sep 21 '15 18:09 satya164

@satya164 I've just added Android support to react-native-icons so you can use icon fonts.

As for custom fonts in general, CustomStyleSpan.java is where typefaces are currently set in React Native Android. For fontFamily to properly work with a custom font, RN would need some way to register a custom font family name with a font file in /assets when setting up the ReactInstanceManager.

Something like:

 mReactInstanceManager = ReactInstanceManager.builder()
  .setApplication(getApplication())
  .setBundleAssetName("index.android.bundle")
  .setJSMainModuleName("index.android")
  .addPackage(new MainReactPackage())

  // Add a font family name associated to a font file in /assets
  .addTypeFace("CustomFont", "Custom-Font.ttf")  

  .setUseDeveloperSupport(BuildConfig.DEBUG)
  .setInitialLifecycleState(LifecycleState.RESUMED)
  .build();

corymsmith avatar Sep 29 '15 14:09 corymsmith

@corymsmith Awesome man. Thanks a ton.

satya164 avatar Sep 29 '15 16:09 satya164

// Add a font family name associated to a font file in /assets .addTypeFace("CustomFont", "Custom-Font.ttf")

Does it work with 0.11.4? For me compiler cannot find this method on Builder instance

vovacodes avatar Oct 09 '15 16:10 vovacodes

@wizardzloy It's just a concept.

satya164 avatar Oct 09 '15 16:10 satya164

@wizardzloy I was merely proposing a way to handle that but it hasn't been implemented

corymsmith avatar Oct 09 '15 16:10 corymsmith