We often do the custom control, some of the controls need to be displayed together, the display text will definitely use the DrawText method, and DrawText (str, x, y, paint) has two parameters x and y is the coordinates of the drawing, we must determine the coordinates, To know where to draw, sometimes we draw a string, and want to re-draw after the string, we need to retrieve the drawing coordinates, this time the first thought is to get the previous string drawing width + The previous string's drawing coordinates can calculate the coordinates we are drawing now.
String str = "Hello"; Canvas.drawtext (str, x, y, mpaint);//1. Rough calculation of text width:floatwidth =Mpaint.measuretext (str);//2. Calculate the text of the rectangle, you can get a wide height:Rect rect =NewRect (); Mpaint.gettextbounds (str,0, Str.length (), rect);intW =rect.width ();inth =rect.height ();//3. Accurately calculate the width of the text: Public Static intgettextwidth (Paint mpaint, String str) {floatIsum = 0; if(str! =NULL&&!str.equals ("")) { intLen =str.length (); floatWidths[] =New float[Len]; Paint.gettextwidths (str, widths); for(inti = 0; i < Len; i++) {isum+=Math.ceil (Widths[i])}} return(int) isum;}
Android Notes 3 ways to calculate the width of a drawtext string when customizing a control