In Jetpack Compose, how do i apply a font/typeface stored in Assets?

Viewed 2565

In Jetpack compose, the documentation suggests applying fonts using the font-family attributes and referring to font files stored in res/fonts folder. Is it also possible to use font files stored under assets/ ?

3 Answers

Yes there is default method which takes AssetManager as an argument:

/**
 * Create a Font declaration from a file in the assets directory. The content of the [File] is
 * read during construction.
 *
 * @param assetManager Android AssetManager
 * @param path full path starting from the assets directory (i.e. dir/myfont.ttf for
 * assets/dir/myfont.ttf).
 * @param weight The weight of the font. The system uses this to match a font to a font request
 * that is given in a [androidx.compose.ui.text.SpanStyle].
 * @param style The style of the font, normal or italic. The system uses this to match a font to a
 * font request that is given in a [androidx.compose.ui.text.SpanStyle].
 */
@ExperimentalTextApi
@OptIn(InternalPlatformTextApi::class, ExperimentalTextApi::class)
@Stable
fun Font(
    assetManager: AssetManager,
    path: String,
    weight: FontWeight = FontWeight.Normal,
    style: FontStyle = FontStyle.Normal
): Font = AndroidAssetFont(assetManager, path, weight, style)

now access font like this!

@OptIn(ExperimentalTextApi::class)
@Composable
fun fontFamily() = FontFamily(
    Font(LocalContext.current.assets,"myfont.ttf")
)

@Composable
fun typography() = Typography(

    h1 = TextStyle(
        fontFamily = fontFamily(),
        fontWeight = FontWeight.Bold,
        fontSize = 30.sp
    )
)

Actually in compose, there is usually a class named Typography.kt, which is used by the MaterialTheme Composable. As described in the Theme Codelab, the correct way is to modify this class to add your fonts to it. You see actually, you can create your own mAppTheme to override Material's.

https://youtu.be/DDd6IOlH3io?t=6m27s

This video showcases implementing custom color palettes, but a similar approach can be taken to implement custom typography.

Check the JetSnack sample app https://github.com/android/compose-samples

  1. Create font directory in res (res/font)

  2. copy your .ttf fonts in res/font

  3. find the Type.kt file ( in ui/theme directory )

  4. create a variable for font in Type.kt

    val MyCustomFont = FontFamily(
        Font(R.font.regular),
        Font(R.font.bold,FontWeight.Bold)
    )
    
  5. there is Typography val in Type.kt file, you can change the entire app's font family by putting defaultFontFamily = MyCustomFont in this val

    val Typography = Typography(
        defaultFontFamily = MyCustomFont,
        body1 = TextStyle(
            fontFamily = MyCustomFont2,
            fontWeight = FontWeight.Normal,
            fontSize = 16.sp
     ),
    
  6. you can set font family to specific typography like body1, h1, h2, ...

Related