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/
?
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
)
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With