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

讓 TextView 中的 ImageSpan 圖片與文字垂直居中

編輯:關於 Android 程式設計

做過「標籤 + 標題」這種排版的人大概都遇過同一個問題:用 TextView 搭配 ImageSpan 把圖示放在文字前面,圖示總是偏上或偏下,怎麼調 margin、padding 都對不齊。原因是 ImageSpan 預設的對齊方式依賴字型度量,跟圖片本身高度沒有關係。

解法是自訂一個 ImageSpan,改寫 getSize() 來控制它佔據的行高與基線位置,再改寫 draw() 決定實際繪製時的 Y 位移。

/**
 * 垂直居中的 ImageSpan
 */
public class VerticalImageSpan extends ImageSpan {

    public VerticalImageSpan(Drawable drawable) {
        super(drawable);
    }

    @Override
    public int getSize(Paint paint, CharSequence text, int start, int end,
                       Paint.FontMetricsInt fontMetricsInt) {
        Drawable drawable = getDrawable();
        Rect rect = drawable.getBounds();
        if (fontMetricsInt != null) {
            Paint.FontMetricsInt fmPaint = paint.getFontMetricsInt();
            int fontHeight = fmPaint.bottom - fmPaint.top;
            int drHeight = rect.bottom - rect.top;
            int top = drHeight / 2 - fontHeight / 4;
            int bottom = drHeight / 2 + fontHeight / 4;

            fontMetricsInt.ascent = -bottom;
            fontMetricsInt.top = -bottom;
            fontMetricsInt.bottom = top;
            fontMetricsInt.descent = top;
        }
        return rect.right;
    }

    @Override
    public void draw(Canvas canvas, CharSequence text, int start, int end,
                     float x, int top, int y, int bottom, Paint paint) {
        Drawable drawable = getDrawable();
        canvas.save();
        int transY = ((bottom - top) - drawable.getBounds().bottom) / 2 + top;
        canvas.translate(x, transY);
        drawable.draw(canvas);
        canvas.restore();
    }
}

兩個方法各自負責什麼

getSize() 回報的是這個 span 要佔多寬,同時可以透過 fontMetricsInt 告訴 TextView「這一行的高度應該怎麼算」。這裡的做法是讓圖片高度取代原本的字型高度,於是行高會被撐開到足以容納圖示,避免圖片被裁切。

draw() 則負責實際畫上去的位置。bottom - top 是該行的總高,減掉圖片高度再除以二,就是讓圖片在行內垂直居中的位移量。

使用方式

Drawable icon = getResources().getDrawable(R.drawable.ic_tag);
icon.setBounds(0, 0, icon.getIntrinsicWidth(), icon.getIntrinsicHeight());

SpannableString ss = new SpannableString("[標籤] 這是一段標題文字");
ss.setSpan(new VerticalImageSpan(icon), 0, 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

TextView tv = findViewById(R.id.title);
tv.setText(ss);

有兩個細節要注意:呼叫前一定要先 setBounds(),否則 getBounds() 拿到的是空的矩形,圖什麼都不會畫;另外 span 的範圍要選對,把範圍設在含文字的位置會讓整段文字都被當成圖示處理。若圖示本身帶有內距,讓它與文字之間有呼吸空間,也可以直接在 drawable 的 bounds 右側多留幾個像素,不必再動 TextView 的 margin。

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