[英]How do i apply a default font to all Text() elements in the app using Jetpack Compose?
[英]In Jetpack Compose, how do i apply a font/typeface stored in Assets?
在 Jetpack compose 中,文档建议使用font-family
属性应用字体并引用存储在res/fonts
文件夹中的字体文件。 是否也可以使用存储在assets/
下的字体文件?
是的,有一个默认方法将AssetManager
作为参数:
/**
* 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)
现在访问这样的字体!
@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
)
)
实际上在 compose 中,通常有一个名为 Typography.kt 的类,供MaterialTheme
Composable 使用。 如主题代码实验室中所述,正确的方法是修改此类以将您的字体添加到其中。 实际上,您可以创建自己的mAppTheme
来覆盖 Material 的。
https://youtu.be/DDd6IOlH3io?t=6m27s
该视频展示了如何实现自定义调色板,但也可以采用类似的方法来实现自定义排版。
检查 JetSnack 示例应用程序https://github.com/android/compose-samples
在 res (res/font) 中创建字体目录
在 res/font 中复制你的 .ttf 字体
找到 Type.kt 文件(在 ui/theme 目录中)
在 Type.kt 中为字体创建一个变量
val MyCustomFont = FontFamily( Font(R.font.regular), Font(R.font.bold,FontWeight.Bold) )
Type.kt 文件中有 Typography val,您可以通过将 defaultFontFamily = MyCustomFont 放入此 val 来更改整个应用程序的字体系列
val Typography = Typography( defaultFontFamily = MyCustomFont, body1 = TextStyle( fontFamily = MyCustomFont2, fontWeight = FontWeight.Normal, fontSize = 16.sp ),
您可以将字体系列设置为特定的排版,例如 body1、h1、h2、...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.