Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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/?

like image 226
Vinay W Avatar asked Sep 12 '25 07:09

Vinay W


1 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
    )
)
like image 74
timr Avatar answered Sep 13 '25 23:09

timr