標籤:android c class blog code java
android 中使用Canvas的drawText繪製文本的位置,是基於基準的。如:
其中字母Q的小尾巴在橫線下面了。
怎麼樣找准字母的中心位置呢?
先看下面的例子:(右邊的數字,表示字型的 left, top, right, bottom)
這裡面的關鍵是Paint.getTextBound。 getTextBound會填充一個Rect,這個Rect表示的就是一個字的left, top, right, bottom。注意到left和top並不是從0,0開始的。 left和right應該是從0座標開始的,而top和bottom相對於基準而言的。這個資訊足夠我們找准文字的中心了。
最後上一下代碼:
@Overridepublic 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);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);}}}