Android draws a string to the center of a custom view

Source: Internet
Author: User
<span id="Label3"></p><p><p>Dealing with the length and width of the string is not as simple as it might seem, and it's not that easy to tell the string to the center of the custom view!</p></p><span id="OSC_h5_1"><span id="OSC_h5_1"></span></span>1. Calculating the length of a string<p><p>Introduce two methods of calculation, but the result is very unexpected oh!</p></p><p><p>(1) Minimum external rectangle<br></p></p><pre><p><span style="color:#660e7a;font-weight:bold;"><span style="color:#660e7a;font-weight:bold;">Paint</span></span>. Settextsize (<span style="color:#660e7a;font-weight:bold;"><span style="color:#660e7a;font-weight:bold;">textSize</span></span>);<br><span style="color:#660e7a;font-weight:bold;"><span style="color:#660e7a;font-weight:bold;">Paint</span></span>. Settypeface (Typeface.<span style="color:#660e7a;font-weight:bold;font-style:italic;"><span style="color:#660e7a;font-weight:bold;font-style:italic;">monospace</span></span>);<br>Rect r =<span style="color:#000080;font-weight:bold;"><span style="color:#000080;font-weight:bold;">New</span></span>Rect ();<br><span style="color:#660e7a;font-weight:bold;"><span style="color:#660e7a;font-weight:bold;">Paint</span></span>. Gettextbounds (<span style="color:#660e7a;font-weight:bold;"><span style="color:#660e7a;font-weight:bold;">text</span></span>,<span style="color:#0000ff;"><span style="color:#0000ff;">0</span></span>,<span style="color:#660e7a;font-weight:bold;"><span style="color:#660e7a;font-weight:bold;">text</span></span>. length (), r);<br><span style="color:#000080;font-weight:bold;"><span style="color:#000080;font-weight:bold;">int</span></span>Height = R.<span style="color:#660e7a;font-weight:bold;"><span style="color:#660e7a;font-weight:bold;">Bottom</span></span>-r.<span style="color:#660e7a;font-weight:bold;"><span style="color:#660e7a;font-weight:bold;">Top</span></span>;<br><span style="color:#000080;font-weight:bold;"><span style="color:#000080;font-weight:bold;">int</span></span>width = R.<span style="color:#660e7a;font-weight:bold;"><span style="color:#660e7a;font-weight:bold;"></span> right</span>-r.<span style="color:#660e7a;font-weight:bold;"><span style="color:#660e7a;font-weight:bold;"></span> left</span>;</p></pre><p><p>(2) using FontMetrics</p></p><pre><pre>Paint.fontmetrics fm = paint.getfontmetrics (); float textWidth = paint.measuretext (text); float textHeight = FM.BOTTOM-FM . top;</pre></pre><p><p>Note: the results of the calculation methods of the two methods will be very different, what is the reason? According to my guess Ah ... The first method is to calculate the minimum size of the string, which is the smallest bounding rectangle that encloses the string (which can be used to calculate the actual length and width of the string), and the second is the Foreigner's calculation of their letters, and the letters A,B,J how to calculate its height? Does A,b,j have an algorithm that calculates its height? Impossible ah, The display is also not beautiful, at least in accordance with the letter j, the missing parts of a and b, so that all the letters are a height, foreigners think of a rut, the entire height of the letter into several parts (think of the primary school to write pinyin), you want what to deal with, such as: descent, Ascent,top,bottom and leading, These things are encapsulated in the FontMetrics class. The following are the two kinds of algorithms.</p></p><p><p><br></p></p><p style="text-align:center"><p style="text-align:center"></p></p><p style="text-align:center"><p style="text-align:center"></p></p><span id="OSC_h5_2"><span id="OSC_h5_2"></span></span>2. Custom View<p><p>Customizing a circle</p></p><pre>circle view {    private string text             =  "handsome";     private int textcolor           = color.black;    private  int textSize           = 0;     private PointF center          =  new pointf (0.0f, 0.0f);    private float strokewidth       = 0.0f;    private float radius            = 0.0f;    private int fillcolor           = color.red;    private  int strokecolor        = color.green;    private  Paint paint;    public circle (context context)  {          (context, );    }    public  Circle (context context, attributeset attrs)  {          (context, attrs, );     }    public circle (context  context, attributeset attrs, defstyleattr)  {          (context, attrs, defstyleattr);         Typedarray ta = context.obtainstyledattributes (attrs,r.styleable.);         count = ta.getindexcount ();         for (int i=0; i<count;&nbsP;i++)  {            int attr =  ta.getindex (i);             switch (attr)  {                case  R.styleable.Circle_text:                     text = ta.getstring (attr);                     break;                 case  r.styleable.circle_textsize:                     textSize =  (int) ta.getdimension (attr,0.0f);                     break;                 case R.styleable.Circle_textColor:                      Textcolor = ta.getcolor (attr, color.black);                     break;                 case R.styleable.Circle_radius:                      radius = ta.getdimension (attr, 0.0f);                     break;                 case r.styleable.circle_strokewidth:                     strokeWidth =  Ta.getdimension (attr, 0.0f);                     break;                 case R.styleable.Circle_fillColor:                     fillcolor  = ta.getcolor (attr, color.red);                     break;                 case R.styleable.Circle_strokeColor:          &Nbsp;          strokecolor = ta.getcolor (attr,  0);                     break;                 default:                     break;             }        }         Ta.recycle ();         init (context);    }     private void init (context context)  {         paint = new paint (paint.anti_alias_flag);    }      @Override      protected void ondraw (canvas canvas)  {         if (radius <= 0)  {             return;        }             float cx = center.x + radius;         float cy = center.y + radius;         //fill        paint.setcolor (fillColor);         paint.setstyle (Paint.Style.FILL);         canvas.drawcircle (cx, cy, radius, paint);         Text        if (!text.isempty () && textsize>0)  {     &nBsp;       paint.setcolor (textcolor);             paint.settextsize (textSize);             paint.settypeface (typeface.monospace);             rect r = new rect ();             paint.gettextbounds (text,0,text.length (), r);             int height = r.bottom - r.top;             int width = r.right -  r.left;            paint.fontmetrics fm  = paint.getfontmetrics ();             float  textwidth = p Aint.measuretext (text);            float  textheight = fm.bottom - fm.top;             float offsetX = width / 2;             float offsetY = height/2 -  (fm.bottom -   (textheight - height)/2);             canvas.drawtext (text, cx-offsetx, cx+offsety, paint);         }        //stroke         if (strokewidth > 0)  {             paint.setcolor (strokecolor);             paint.setstrokewidth (strokewidth);             paint.setstyle (Paint.Style.STROKE);             canvas.drawcircle (cx, cy,  radius, paint);         }    }</pre><p><p>The above is just part of the code to see the OnDraw method. I've drawn a circle and stroked it, and I've drawn a string inside the circle, so that the center of the word is Centered. In the center of the word, but walk a way, see the following diagram (see the above code offsety).</p></p><p style="text-align:center"><p style="text-align:center"></p></p><p><p>As can be seen clearly, the y direction should offset the amount: OffsetY = h2/2-(bh-(h1-h2)/2).</p></p><span id="OSC_h5_3"><span id="OSC_h5_3"></span></span>3. Effects<p style="text-align:center"><p style="text-align:center"></p></p><p><p><br></p></p><p><p>Android draws a string to the center of a custom view</p></p></span>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.