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

Canvas.drawText 的基線陷阱:精準定位文字中心

編輯:關於 Android 程式設計

Android 中用 Canvas 的 drawText 繪製文字,座標定位是基於基線(baseline)而非文字外框左上角。這點很容易被忽略,於是就出現下圖這種狀況——字母 Q 的小尾巴掉到橫線下面去了。

關鍵在 Paint.getTextBounds

getTextBounds 會把結果填進一個 Rect,內容就是這個字的 left、top、right、bottom。要特別注意:left 與 top 並不是從 (0, 0) 起算——left 與 right 大致從 0 座標出發,而 top 與 bottom 是相對基線而言的(因此 top 通常為負值)。

掌握這件事,資訊就夠了:想讓文字的中心對齊某個座標點,只要用 (left + right) / 2 修正 X、(top + bottom) / 2 修正 Y,再把基線座標減掉這兩個偏移量即可。

示範程式碼

@Override
public void onDraw(Canvas canvas) {
    mPaint.setTextSize(40f);
    mPaint.setAntiAlias(true);
    mPaint.setColor(0xffff0000);
    canvas.drawText(alphas, 30, 60, mPaint);
    mPaint.setColor(0xff000000);
    canvas.drawLine(0, 60, 1000, 60, mPaint);

    for (int i = 0; i < alphas.length(); i++) {
        int y = i * 70 + 100;
        mPaint.getTextBounds(alphas, i, i + 1, mBound);
        mPaint.setColor(0xff000000);
        canvas.drawText(String.format("%d,%d,%d,%d",
                mBound.left, mBound.top, mBound.right, mBound.bottom), 150, y, mPaint);

        mPaint.setColor(0xffff0000);
        canvas.drawCircle(60, y, 30, mPaint);

        mPaint.setColor(0xffffffff);
        // 用 bounds 中心反推基線座標,讓白字精準落在紅圈中心
        canvas.drawText(alphas, i, i + 1,
                60 - (mBound.right + mBound.left) / 2,
                y  - (mBound.bottom + mBound.top) / 2,
                mPaint);

        mPaint.setColor(0xff000000);
        canvas.drawLine(30, y, 90, y, mPaint);
        canvas.drawLine(60, y - 30, 60, y + 30, mPaint);
    }
}

程式中同時把 bounds 的四個數值印在畫面上,方便一眼對照基線、外框與實際落點之間的關係。這套算法在自繪按鈕、標籤、頭像邊框等需要文字完美居中的場景中很常用。

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