The location of the DrawText drawing text using canvas in Android is based on the baseline. Such as:
The small tail of the letter Q is below the line.
How do you find the central position of the letter?
Let's take a look at the following example: (the number on the right, the left of the font, top, bottom)
The key to this is paint.gettextbound. Gettextbound fills a rect that represents the left, top, right, and bottom of a word. Notice that left and top are not starting from 0, 0. Left and right should start with 0 coordinates, while top and bottom are relative to the baseline. This information is enough for us to find the center of the text.
Finally, the code:
@Overridepublic void OnDraw (canvas canvas) {mpaint.settextsize (40f); Mpaint.setantialias (true); Mpaint.setcolor ( Canvas.drawtext (Alphas, 0xffff0000, 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); MP Aint.setcolor (0xff000000); Canvas.drawtext (String.Format ("%d,%d,%d,%d", Mbound.left,mbound.top, MBound.right, Mbound.bottom), Mpaint, Y, Mpaint.setcolor (0xffff0000), canvas.drawcircle (x, y, X, Mpaint), Mpaint.setcolor ( 0xFFFFFFFF); Canvas.drawtext (Alphas, I, i+1, X-(mbound.right + mbound.left)/2, Y-(mbound.bottom + mbound.top)/2, Mpain t); Mpaint.setcolor (0xff000000); Canvas.drawline ((x, y, N, y, mpaint); Canvas.drawline (y-30, X, y+30, Mpaint);}}