如何将 TextStyle 从 Jetpack Compose 转换为 android.graphics.Typeface?

Bar*_*ski 14 android kotlin android-typeface android-jetpack-compose

我需要Canvas在 Compose 中绘制文本,为此我需要一个TextPaintwith android.graphics.Typeface

有没有办法轻松地将 Compose 转换TextStyle为 a android.graphics.Typeface

小智 12

您可以使用从对象解析android.graphics.Typeface对象。androidx.compose.ui.text.TextStyleLocalFontFamilyResolver

val style: TextStyle = MaterialTheme.typography.body1
val resolver: FontFamily.Resolver = LocalFontFamilyResolver.current

val typeface: Typeface = remember(resolver, style) {
    resolver.resolve(
        fontFamily = style.fontFamily,
        fontWeight = style.fontWeight ?: FontWeight.Normal,
        fontStyle = style.fontStyle ?: FontStyle.Normal,
        fontSynthesis = style.fontSynthesis ?: FontSynthesis.All,
    )
}.value as Typeface
Run Code Online (Sandbox Code Playgroud)