Jetpack Compose-自定义字体

前言

开发过程中我们经常需要替换默认的字体,来达到更好的显示效果。

字体引用

我们下载的字体包

image-20250825143010485

其中HarmonyOS_Sans_SC_Regular.ttf是标准粗细的字体

我们引用这个就行。

字体文件需要放置在 app/src/main/res/font 目录下。

文件名称只能有小写字母和数字,注意改名。

全局字体

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
val displayMetrics = LocalContext.current.resources.displayMetrics
val fontScale = LocalDensity.current.fontScale
val widthPixels = displayMetrics.widthPixels

val configuration = LocalConfiguration.current
val isLandscape = configuration.orientation == Configuration.ORIENTATION_LANDSCAPE
val widthDp = if (isLandscape) 960.0f else 540.0f
val widthDensity = widthPixels / widthDp

// 创建自定义字体族
val customFontFamily = FontFamily(
Font(R.font.harmonyregular),
)
MaterialTheme(
colorScheme = colorScheme,
typography = Typography,
content = {
CompositionLocalProvider(
LocalDensity provides Density(
density = widthDensity,
fontScale = fontScale
),
LocalTextStyle provides MaterialTheme.typography.bodyMedium.copy(
fontFamily = customFontFamily,
fontSize = 16.sp
)
) {
content()
}
}
)

主要生效部分

1
2
3
4
5
6
7
8
9
10
11
// 创建自定义字体族
val customFontFamily = FontFamily(
Font(R.font.harmonyregular),
)

CompositionLocalProvider(
LocalTextStyle provides MaterialTheme.typography.bodyMedium.copy(
fontFamily = customFontFamily,
fontSize = 16.sp
)
)

不同的字重

设置字体的时候,我们可以引用不同字重的字体,也可以只引用标准字体。

当引用了不同字重字体的时候,会自动使用对应字重的字体。

1
2
3
4
5
val customFontFamily = FontFamily(
Font(R.font.harmonyregular, FontWeight.Normal),
Font(R.font.harmonymedium, FontWeight.Medium),
Font(R.font.harmonybold, FontWeight.Bold)
)

当你设置的 FontWeight 与字体文件本身的字重不一致时,系统会尝试通过算法来模拟加粗效果。

如果你使用的是普通字重(FontWeight.Normal)的字体文件,但在代码中设置了 FontWeight.Bold,系统会对文字进行一些简单的处理,如增加笔画的宽度。

设置不生效

Text中不要设置这个,虽然没有设置字体,也会导致全局设置不生效。

1
2
3
4
5
style = TextStyle(
fontSize = size,
// 可选:强制相同的基线对齐策略
baselineShift = BaselineShift.None
)

附录

字体粗细

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/** Alias for [W100] */
@Stable val Thin = W100
/** Alias for [W200] */
@Stable val ExtraLight = W200
/** Alias for [W300] */
@Stable val Light = W300
/** The default font weight - alias for [W400] */
@Stable val Normal = W400
/** Alias for [W500] */
@Stable val Medium = W500
/** Alias for [W600] */
@Stable val SemiBold = W600
/** A commonly used font weight that is heavier than normal - alias for [W700] */
@Stable val Bold = W700
/** Alias for [W800] */
@Stable val ExtraBold = W800
/** Alias for [W900] */
@Stable val Black = W900