Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 字體設置與 Roboto 字體使用指南

編輯:關於 Android 程式設計

字體是界面氣質的重要組成部分。Android 在字體這件事上給了兩條路:加載自定義 TTF 文件,或使用系統自帶的字體族。

一、加載自定義 TTF 字體

通過 Typeface 加載字體文件,分兩步。

第一步,在 assets 目錄下新建 fonts 文件夾,把 ttf 文件放進去。

第二步,在代碼中加載並應用:

AssetManager mgr = getAssets();                       // 得到 AssetManager
Typeface tf = Typeface.createFromAsset(mgr, "fonts/ttf.ttf"); // 按路徑加載
TextView tv = findViewById(R.id.textview);
tv.setTypeface(tf);                                   // 應用字體

這裡有幾個實踐要點:字體文件不宜過大,中文字庫動輒好幾 MB,會明顯拖慢啟動;createFromAsset 每次調用都有 IO 開銷,應把 Typeface 緩存複用而非在 getView 裡反覆加載;更好的做法是在自定義 TextView 中一次性加載,避免處處調用。

二、中文粗體的特殊處理

XML 裡寫 android:textStyle="bold" 可以讓英文變粗體,但對中文往往無效——因為多數中文字體本身沒有提供真正的 bold 字面。

解決辦法是讓系統模擬:

TextView tv = (TextView) findViewById(R.id.TextView01);
tv.getPaint().setFakeBoldText(true); // 中文仿粗體

setFakeBoldText 通過在繪製時做細微的偏移描邊來達到視覺加粗的效果。需要注意兩點:一是部分字體下這種模擬效果並不理想,甚至可能報不出錯但視覺上毫無變化;二是它會略微影響文字渲染的清晰度,小字號下尤其明顯。

三、Roboto 字體族

從 Android 4.0 開始,系統默認字體換成了 Roboto。 Roboto 是為屏幕閱讀優化設計的無襯線字體,字形開闊、易於辨識,同時也是 Material Design 的指定字體。

在 XML 中通過 fontFamily 引用它的各個變體:

android:fontFamily="sans-serif"             // Roboto Regular
android:fontFamily="sans-serif-light"        // Roboto Light
android:fontFamily="sans-serif-condensed"    // Roboto Condensed
android:fontFamily="sans-serif-thin"         // Roboto Thin(Android 4.2+)

再配合 android:textStyle 組合成完整的字重矩陣:

// 可用的 textStyle 取值
normal        // Regular
italic        // Italic
bold          // Bold
bold|italic   // Bold-italic

加上 Light、Light-italic、Thin、Thin-italic,以及 Condensed 系列的 regular / italic / bold / bold-italic,Roboto 一共提供了 12 種風格,足以覆蓋絕大多數排版層次需求。

實踐建議

能用系統字體族就不要引第三方字庫——Roboto 隨系統分發,零包體成本,且在各版本上渲染一致。確實需要品牌字體時,Android 8.0 之後支持把字體作為資源(font resource)或直接打包成 XML 聲明,比早期的 assets 加載方式更規範,也能自動生成對應的 Typeface 緩存。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved