Android中canvas.drawText 繪製文字居中
阿新 • • 發佈:2019-01-04
Android中canvas.drawText 繪製文字居中
因為最近多開專案,時間主要花在 coding 和 review 上了,抽空寫個自定義控制元件中的小案例,但是雖然知識點很小但是在開發中很常用
首先來看這個方法:
drawText(String text, float x, float y, Paint paint)
首先第一個引數 text 是我們需要繪製的文字,第二、三個引數 x,y 是關鍵所在,其含義為:x預設是這個字串的左邊在螢幕的位置,y是指定這個字元baseline在螢幕上的位置。最後第四個引數 paint 是我們的畫筆,用於定義字型、大小、顏色等屬性。
這圖用iPad隨手畫的,可以很清楚地看出x和y引數的意義。
那麼怎麼做才能獲取正確的居中位置呢,這裡需要一些運算,直接上程式碼:
@Override
protected void onDraw(Canvas canvas) {
String testString = "測試文字";
//設定要繪製的字型
Paint mPaint = new Paint();
mPaint.setTypeface(Typeface.create(Typeface.DEFAULT_BOLD, Typeface.BOLD));
mPaint.setTextSize(30);
mPaint.setColor(ThemeUtil.getThemeColor (context, R.attr.colorAccent));
//將文字用一個矩形包裹,進而算出文字的長和寬
Rect bounds = new Rect();
mPaint.getTextBounds(testString, 0, testString.length(), bounds);
FontMetricsInt fontMetrics = mPaint.getFontMetricsInt();
//計算長寬
int x = getMeasuredWidth() / 2 - bounds.width() / 2;
int y = (getMeasuredHeight() - fontMetrics.bottom + fontMetrics.top) / 2 - fontMetrics.top;
canvas.drawText(testString, x, y, mPaint);
}
在剛開始寫的時候,可能很多人會和我一樣寫成
canvas.drawText(testString, getMeasuredWidth()/2 - bounds.width()/2, getMeasuredHeight()/2 + bounds.height()/2,mPaint);
這不是真正的居中,雖然 y 確實是位於中間,但是會導致文字下沉,其原因還是因為我上面講的 y 不是字元中心,而是baseline在螢幕上的位置。