使用字型

本頁面說明如何在 Compose 應用程式中設定字型。

設定字型

TextfontFamily 參數,可設定在組件中使用的字型。預設使用 Serif、Sans-Serif、等寬字型和草寫字型系列 都包含:

@Composable
fun DifferentFonts() {
    Column {
        Text("Hello World", fontFamily = FontFamily.Serif)
        Text("Hello World", fontFamily = FontFamily.SansSerif)
    }
}

字詞

您可以使用 fontFamily 屬性搭配自訂字型和字體。 在 res/font 資料夾中定義的:

搜尋結果的寫實畫面 >開發環境的字型資料夾

本範例說明如何根據這些字型定義 fontFamily 檔案,以及如何使用 Font 函式

val firaSansFamily = FontFamily(
    Font(R.font.firasans_light, FontWeight.Light),
    Font(R.font.firasans_regular, FontWeight.Normal),
    Font(R.font.firasans_italic, FontWeight.Normal, FontStyle.Italic),
    Font(R.font.firasans_medium, FontWeight.Medium),
    Font(R.font.firasans_bold, FontWeight.Bold)
)

您可以將此 fontFamily 傳遞至 Text 可組合項。由於 fontFamily 可包含不同的粗細,因此您可以手動設定 fontWeight,選取適當的文字粗細:

Column {
    Text(text = "text", fontFamily = firaSansFamily, fontWeight = FontWeight.Light)
    Text(text = "text", fontFamily = firaSansFamily, fontWeight = FontWeight.Normal)
    Text(
        text = "text",
        fontFamily = firaSansFamily,
        fontWeight = FontWeight.Normal,
        fontStyle = FontStyle.Italic
    )
    Text(text = "text", fontFamily = firaSansFamily, fontWeight = FontWeight.Medium)
    Text(text = "text", fontFamily = firaSansFamily, fontWeight = FontWeight.Bold)
}

主題

如要瞭解如何設定整個應用程式的字體排版,請參閱「Compose 中的自訂設計系統」。

可下載的字型

Compose 1.2.0 開始,您可以使用 Compose 應用程式中的可下載字型 API,以非同步方式下載 Google 字型,然後在應用程式中使用。

目前不支援自訂提供者提供的可下載字型。

透過程式輔助方式使用可下載字型

如要在應用程式中以程式輔助方式下載字型,請按照下列步驟操作:

  1. 新增依附元件:
    GroovyKotlin
    dependencies {
        ...
        implementation "androidx.compose.ui:ui-text-google-fonts:1.7.8"
    }
    dependencies {
        ...
        implementation("androidx.compose.ui:ui-text-google-fonts:1.7.8")
    }
  2. GoogleFont.Provider 擁有 Google Fonts 的憑證
    val provider = GoogleFont.Provider(
        providerAuthority = "com.google.android.gms.fonts",
        providerPackage = "com.google.android.gms",
        certificates = R.array.com_google_android_gms_fonts_certs
    )
    供應器收到的參數如下:
    • Google Fonts 的字型提供者授權。
    • 用於驗證供應程式身分的字型供應程式套件。
    • 憑證的雜湊組合清單,用於驗證憑證的身分 。您可以在 JetChat 範例應用程式的 font_certs.xml 檔案中,找到 Google Fonts 供應者所需的雜湊。
  3. 定義 FontFamily
    // ...
     import androidx.compose.ui.text.googlefonts.GoogleFont
     import androidx.compose.ui.text.font.FontFamily
     import androidx.compose.ui.text.googlefonts.Font
     // ...
    
    val fontName = GoogleFont("Lobster Two")
    
    val fontFamily = FontFamily(
        Font(googleFont = fontName, fontProvider = provider)
    )
    您可以使用 屬性來查詢字型的其他參數,例如粗細和樣式 FontWeightFontStyle 分別為:
    // ...
     import androidx.compose.ui.text.googlefonts.GoogleFont
     import androidx.compose.ui.text.font.FontFamily
     import androidx.compose.ui.text.googlefonts.Font
     // ...
    
    val fontName = GoogleFont("Lobster Two")
    
    val fontFamily = FontFamily(
        Font(
            googleFont = fontName,
            fontProvider = provider,
            weight = FontWeight.Bold,
            style = FontStyle.Italic
        )
    )
  4. 設定要在文字可組合函式中使用的 FontFamily

Text(
    fontFamily = fontFamily, text = "Hello World!"
)

您也可以製定 字體排版 您的 FontFamily

val MyTypography = Typography(
    bodyMedium = TextStyle(
        fontFamily = fontFamily, fontWeight = FontWeight.Normal, fontSize = 12.sp/*...*/
    ),
    bodyLarge = TextStyle(
        fontFamily = fontFamily,
        fontWeight = FontWeight.Bold,
        letterSpacing = 2.sp,
        /*...*/
    ),
    headlineMedium = TextStyle(
        fontFamily = fontFamily, fontWeight = FontWeight.SemiBold/*...*/
    ),
    /*...*/
)

接著,請將字體排版設為應用程式的主題:

MyAppTheme(
    typography = MyTypography
)/*...*/

如需在 Compose 中實作可下載字型的應用程式範例 搭配 Material3 請參閱 Jetchat 範例應用程式。

新增備用字型

您可以決定字型的備用鏈,以防字型無法正確下載。例如,如果您已定義可下載的字型 輸入:

// ...
 import androidx.compose.ui.text.googlefonts.Font
 // ...

val fontName = GoogleFont("Lobster Two")

val fontFamily = FontFamily(
    Font(googleFont = fontName, fontProvider = provider),
    Font(googleFont = fontName, fontProvider = provider, weight = FontWeight.Bold)
)

您可以同時定義兩種粗細的字型預設值,如下所示:

// ...
 import androidx.compose.ui.text.font.Font
 import androidx.compose.ui.text.googlefonts.Font
 // ...

val fontName = GoogleFont("Lobster Two")

val fontFamily = FontFamily(
    Font(googleFont = fontName, fontProvider = provider),
    Font(resId = R.font.my_font_regular),
    Font(googleFont = fontName, fontProvider = provider, weight = FontWeight.Bold),
    Font(resId = R.font.my_font_regular_bold, weight = FontWeight.Bold)
)

確認您新增的是正確的匯入項目。

定義這種 FontFamily 會建立一個 FontFamily,其中包含兩個鏈結,每種粗細一個。載入機制會嘗試先解析線上字型,然後再處理本機 R.font 資源資料夾中的字型。

為實作偵錯

為協助您確認字型下載是否正確,您可以定義 偵錯協同程式處理常式。您的控點可提供字型無法以非同步方式載入時的處理方式。

首先,請建立 CoroutineExceptionHandler

val handler = CoroutineExceptionHandler { _, throwable ->
    // process the Throwable
    Log.e(TAG, "There has been an issue: ", throwable)
}

將其傳遞至 createFontFamilyResolver 方法,讓解析器使用新的處理常式:

CompositionLocalProvider(
    LocalFontFamilyResolver provides createFontFamilyResolver(LocalContext.current, handler)
) {
    Column {
        Text(
            text = "Hello World!", style = MaterialTheme.typography.bodyMedium
        )
    }
}

您也可以使用 isAvailableOnDevice 供應商提供的 API,用於測試供應商是否可用,以及憑證是否 正確設定。方法是呼叫 isAvailableOnDevice 方法 如果供應器設定有誤,則會傳回 false。

val context = LocalContext.current
LaunchedEffect(Unit) {
    if (provider.isAvailableOnDevice(context)) {
        Log.d(TAG, "Success!")
    }
}

注意事項

Google Fonts 需要數個月的時間才能在 Android 上提供新字型。當字型在 fonts.google.com 中新增後,需要一段時間才可透過可下載字型 API 提供 (在 View 系統或 Compose 中)。新上榜 在應用程式中載入的字型和文字 IllegalStateException。 為了協助開發人員判斷該錯誤,並與其他類型的字型載入錯誤進行比較,我們已針對 Compose 使用這裡的變更新增例外狀況訊息。如果發現任何問題,請使用 追蹤器

使用可變字型

變數字型是一種字型格式,可讓一個字型檔案包含不同的樣式。透過可變字型,您可以修改軸 (或參數) 以產生 您偏好的風格這些軸可以是標準值,例如重量、寬度、斜體 以及文字,這會因變數字型而異

具有相同可變字型、不同軸值的五項設定。
圖 1. 使用相同變數字型,並以不同軸值自訂的文字。

使用可變字型而非一般字型檔案,可讓您只使用一個字型檔案,而非多個字型檔案。

如需更多可變字型的背景資訊,請參閱 Google Fonts 知識:涵蓋的完整目錄 可變字型,以及每種詞彙支援的軸

本文說明如何在 Compose 應用程式中實作可變字型。

載入變數字型

  1. 請下載要使用的變數字型 (例如 Roboto Flex),並將其放入應用程式中的 app/res/font 資料夾。請確認 .您新增的 ttf 檔案是字型的變數字型版本,且字型檔案名稱全為小寫,且不含任何特殊字元。

  2. 如果要載入變數字型,請使用 FontFamily res/font/ 目錄:

    // In Typography.kt
    @OptIn(ExperimentalTextApi::class)
    val displayLargeFontFamily =
        FontFamily(
            Font(
                R.font.robotoflex_variable,
                variationSettings = FontVariation.Settings(
                    FontVariation.weight(950),
                    FontVariation.width(30f),
                    FontVariation.slant(-6f),
                )
            )
        )

    FontVariation API 可讓您設定標準字型軸,例如粗細寬度斜度。這些是標準的軸 所有可變字型都能使用您也能針對 Cloud Build 根據該字型使用的位置決定合適的字型

  3. 變數字型僅適用於 Android O 以上版本,因此請新增 並設定適當的備用選項:

    // In Typography.kt
    val default = FontFamily(
        /*
        * This can be any font that makes sense
        */
        Font(
            R.font.robotoflex_static_regular
        )
    )
    @OptIn(ExperimentalTextApi::class)
    val displayLargeFontFamily = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        FontFamily(
            Font(
                R.font.robotoflex_variable,
                variationSettings = FontVariation.Settings(
                    FontVariation.weight(950),
                    FontVariation.width(30f),
                    FontVariation.slant(-6f),
                )
            )
        )
    } else {
        default
    }

  4. 將設定擷取為一組常數,以便於重複使用及取代 使用以下常數的字型設定:

    // VariableFontDimension.kt
    object DisplayLargeVFConfig {
        const val WEIGHT = 950
        const val WIDTH = 30f
        const val SLANT = -6f
        const val ASCENDER_HEIGHT = 800f
        const val COUNTER_WIDTH = 500
    }
    
    @OptIn(ExperimentalTextApi::class)
    val displayLargeFontFamily = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        FontFamily(
            Font(
                R.font.robotoflex_variable,
                variationSettings = FontVariation.Settings(
                    FontVariation.weight(DisplayLargeVFConfig.WEIGHT),
                    FontVariation.width(DisplayLargeVFConfig.WIDTH),
                    FontVariation.slant(DisplayLargeVFConfig.SLANT),
                )
            )
        )
    } else {
        default
    }

  5. 將 Material Design 3 的字體排版設為使用 FontFamily

    // Type.kt
    val Typography = Typography(
        displayLarge = TextStyle(
            fontFamily = displayLargeFontFamily,
            fontSize = 50.sp,
            lineHeight = 64.sp,
            letterSpacing = 0.sp,
            /***/
        )
    )

    此範例採用 displayLarge Material 3 字體排版, 預設字型設定和建議用途舉例來說,您應該使用 displayLarge 代表簡短且重要的文字,因為這是螢幕上的最大文字。

    使用 Material 3 時,您可以變更 TextStylefontFamily 的預設值,自訂字體排版。在上方的程式碼片段中 TextStyle 例項,可自訂每個字型系列的字型設定。

  6. 定義字體排版後,請將其傳遞至 M3 MaterialTheme

    MaterialTheme(
        colorScheme = MaterialTheme.colorScheme,
        typography = Typography,
        content = content
    )

  7. 最後,使用 Text 可組合函式,並將樣式指定為其中一個已定義的 字體排版樣式 MaterialTheme.typography.displayLarge

    @Composable
    @Preview
    fun CardDetails() {
        MyCustomTheme {
            Card(
                shape = RoundedCornerShape(8.dp),
                elevation = CardDefaults.cardElevation(defaultElevation = 4.dp),
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(16.dp)
            ) {
                Column(
                    modifier = Modifier.padding(16.dp)
                ) {
                    Text(
                        text = "Compose",
                        style = MaterialTheme.typography.displayLarge,
                        modifier = Modifier.padding(bottom = 8.dp),
                        maxLines = 1
                    )
                    Text(
                        text = "Beautiful UIs on Android",
                        style = MaterialTheme.typography.headlineMedium,
                        modifier = Modifier.padding(bottom = 8.dp),
                        maxLines = 2
                    )
                    Text(
                        text = "Jetpack Compose is Android’s recommended modern toolkit for building native UI. It simplifies and accelerates UI development on Android. Quickly bring your app to life with less code, powerful tools, and intuitive Kotlin APIs.",
                        style = MaterialTheme.typography.bodyLarge,
                        modifier = Modifier.padding(bottom = 8.dp),
                        maxLines = 3
                    )
                }
            }
        }
    }

    每個 Text 可組合函式都會透過 Material Design 主題的樣式設定, 則含有不同的字型設定。別擔心!您可以使用 MaterialTheme.typography:擷取提供給 M3 的字體排版 MaterialTheme 可組合函式。

三種文字,分別顯示不同的字型設定。
圖 2. 已於三種不同設定套用變數字型。

使用自訂軸

字型也可以有自訂軸。這些資訊會在字型檔案中定義。舉例來說,Roboto Flex 字型有上升線高度 ("YTAS") 軸,可調整小寫字母上升線的高度,而對稱區寬度 ("XTRA") 則可調整每個字母的寬度。

您可以透過 FontVariation 設定變更這些軸的值。

如要進一步瞭解可為字型設定的自訂軸,請參閱各字型的支援軸表格

  1. 如要使用自訂軸,請為自訂 ascenderHeightcounterWidth 軸定義函式:

    fun ascenderHeight(ascenderHeight: Float): FontVariation.Setting {
        require(ascenderHeight in 649f..854f) { "'Ascender Height' must be in 649f..854f" }
        return FontVariation.Setting("YTAS", ascenderHeight)
    }
    
    fun counterWidth(counterWidth: Int): FontVariation.Setting {
        require(counterWidth in 323..603) { "'Counter width' must be in 323..603" }
        return FontVariation.Setting("XTRA", counterWidth.toFloat())
    }

    這些函式可執行以下操作:

    • 定義防護機制可以接受的值。如同 變數字型目錄ascenderHeight (YTAS) 具有 最小值為 649f,最大值為 854f
    • 傳回字型設定,讓設定可加入字型。於 FontVariation.Setting() 方法,軸名稱 (YTAS, XTRA) 是 並將值視為參數
  2. 搭配使用軸和字型設定,將其他參數傳送至 每個載入的 Font

    @OptIn(ExperimentalTextApi::class)
    val displayLargeFontFamily = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        FontFamily(
            Font(
                R.font.robotoflex_variable,
                variationSettings = FontVariation.Settings(
                    FontVariation.weight(DisplayLargeVFConfig.WEIGHT),
                    FontVariation.width(DisplayLargeVFConfig.WIDTH),
                    FontVariation.slant(DisplayLargeVFConfig.SLANT),
                    ascenderHeight(DisplayLargeVFConfig.ASCENDER_HEIGHT),
                    counterWidth(DisplayLargeVFConfig.COUNTER_WIDTH)
                )
            )
        )
    } else {
        default
    }

    請注意,小寫字母升部的高度現在已增加,其他文字的寬度也變寬:

三個不同的文字顯示變數字型不同的設定,並設定自訂軸線,其中有些字母的小寫升部字母較高,且比先前更寬。
圖 3.顯示可變字型設定的自訂軸文字。

其他資源

如需詳細資訊,請參閱下列有關可變字型的網誌文章:

目前沒有任何建議。

建議 Google 帳戶。