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

如何取得 TextView 顯示字符串的真實寬度

編輯:關於 Android 程式設計

有一個需求是:判斷 TextView 要顯示的文字寬度是否超過設定值,超過就手動換行。實作時發現,用哪種方式量文字寬度,結果會不一樣——而差的那一兩個像素,足以讓換行判斷出錯。

直覺寫法:new 一個 TextPaint

public float getTextWidth(Context context, String text, int textSize) {
    TextPaint paint = new TextPaint();
    float scaledDensity = context.getResources().getDisplayMetrics().scaledDensity;
    paint.setTextSize(scaledDensity * textSize);
    return paint.measureText(text);
}

用的是 TextPaint.measureText()。邏輯上沒問題,但實測時發現:當字串中混有英文字母與數字,結果會有 1–2 像素的誤差。就是這點誤差,讓「是否超過寬度」的判斷在邊界處翻轉,介面上該換行的地方沒換,或反之。

改用 TextView 自己的 Paint

關鍵在於:每個 TextView 都已經持有一個經過完整設定的 TextPaint 物件,可以透過 getPaint() 取得。它已經套用好了字型、字重、字距、textScaleFactor 等所有影響測量的參數,量出來的結果自然與實際繪製一致。

TextPaint textPaint = textView.getPaint();
float textPaintWidth = textPaint.measureText(text);

兩種方法的實測對比

測試機為 MI4(xxdpi),字級 15sp,同時印出三個數字做對照:TextView 自己的 getMeasuredWidth()、新建 TextPaint 的 measureText()、以及 TextView 內建 Paint 的 measureText()。

public class MainActivity extends Activity {

    private static final String TAG = "MainActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        TextView textView = (TextView) findViewById(R.id.test);
        textView.setText("測試英文abcd");
        textView.setTextSize(15);

        // 1. 讓 TextView 自行量測
        int spec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
        textView.measure(spec, spec);
        int measuredWidth = textView.getMeasuredWidth();

        // 2. 新建 TextPaint 量測
        TextPaint newPaint = new TextPaint();
        float textSize = getResources().getDisplayMetrics().scaledDensity * 15;
        newPaint.setTextSize(textSize);
        float newPaintWidth = newPaint.measureText("測試英文abcd");

        // 3. 用 TextView 內建的 Paint 量測
        float textPaintWidth = textView.getPaint().measureText("測試英文abcd");

        Log.i(TAG, "getMeasuredWidth      : " + measuredWidth);
        Log.i(TAG, "newPaint measureText  : " + newPaintWidth);
        Log.i(TAG, "getPaint measureText  : " + textPaintWidth);
    }
}

純中文「測試中文」:

getMeasuredWidth      : 180
newPaint measureText  : 180.0
getPaint measureText  : 180.0

三者一致,因為中文是等寬字元,誤差被掩蓋了。

中英混雜「測試英文abcd」:

getMeasuredWidth      : 279
newPaint measureText  : 278.0
getPaint measureText  : 279.0

差異就出現了:新建的 TextPaint 少了 1 像素,而 TextView 內建 Paint 的結果與 getMeasuredWidth() 完全吻合。

結論與延伸

要預估文字繪製後的實際寬度,請用 textView.getPaint().measureText(text),不要自己 new 一個 TextPaint。原因是自建的 Paint 缺少 TextView 已套用的各項設定(字型家族、字重、textScaleFactor、letter spacing 等),在含非等寬字元的字串上就會產生偏差。

如果你只是想知道「這段文字在這個寬度下會不會換行」,其實有更準的工具:StaticLayout 或 DynamicLayout 能直接依給定寬度算出換行後的行數與高度;Paint.breakText() 則可以問出「在這麼寬的空間內能放幾個字」。這兩個 API 比手動累加寬度更貼近 TextView 的實際排版行為。

另外提醒:文字寬度會隨使用者的系統字級設定(font scale)而變。若你的判斷邏輯對此敏感,記得每次都從 TextView 即時取值,別在初始化時把寬度快取下來。

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