Translation with the original address of Chris Banes's blog
If you want to manually draw something on Android canvas, you'd better start by drawing text.
Before the text is drawn, you need to know where to draw the measured text and calculate the position of the text x/Y axis.
Recently in an app, I need to draw some text-centric texts on the landscape and portrait canvas. So I used the following code:
Paint Mtextpaint = new paint (); Mtextpaint.settextalign (Paint.Align.CENTER); Center The text//later when you Draw...canvas.drawtext (MText,//text to display Mbounds.centerx (),//center X of Canvas bounds mbounds.centery (),//Center Y of canvas bounds mtextpaint);
I did not expect the code to run after the following looks like this:
Measurement text
Next, I try to position the text, calculate the high width of the text, and modify the position of the x-axis y-axis of the drawing text:
int Mtextwidth, mtextheight; Our calculated text bounds Paint mtextpaint = new paint ();//Now lets calculate the size of the Textrect textbounds = new Rect (); Mtextpaint.gettextbounds (mText, 0, Mtext.length (), textbounds); Mtextwidth = Textbounds.width (); Mtextheight = Textbounds.height ();//later when you Draw...canvas.drawtext (MText,//Text to display Mbounds.centerx ()-(mtextwidth/2f), mbounds.centery () + (mtextheight/2f), mtextpaint);
This time we've done pretty close, but you can see that the text is still not centered.
To determine why I didn't see it, I used Paint.gettextbounds () to calculate a rectangle and draw it behind the text.
As you can see, the aspect of the text is drawn outside of the computed range.
Another way to measure text
On this base point, I see Paint another way to calculate the width of text: Paint.measuretext ()
This method only calculates the width and cannot calculate the height, so I try to combine two methods:
int Mtextwidth, mtextheight; Our calculated text bounds Paint mtextpaint = new paint ();//Now lets calculate the size of the Textrect textbounds = new Rect (); Mtextpaint.gettextbounds (mText, 0, Mtext.length (), textbounds); Mtextwidth = Mtextpaint.measuretext (MText); Use Measuretext to calculate width mtextheight = textbounds.height (),//Use height from gettextbounds ()//later WH En draw...canvas.drawtext (mText,//Text to display Mbounds.centerx ()-(mtextwidth/2f), mbounds.centery () + (mtextheight/2f), mtextpaint);
This makes the text perfectly centered. Hey, yo!