In android, the position of the text to be drawn using the drawText of Canvas is baseline-based. For example:
The tail of the letter Q is below the horizontal line.
<喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> VcD4KPHA + forward + z8i/tM/Cw + forward + CjxwPjxpbWcgc3JjPQ = "http://www.2cto.com/uploadfile/Collfiles/20140607/2014060709072586.jpg" alt = "\">
The key here is Paint. getTextBound. GetTextBound will fill in a Rect, which indicates the left, top, right, and bottom of a word. Note that left and top do not start from 0 to 0. Left and right should start from the 0 coordinate, while top and bottom are relative to the baseline. This information is enough for us to find the center of the text.
The last code is as follows:
@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);}}}