Android Notes 3 ways to calculate the width of a drawtext string when customizing a control

Source: Internet
Author: User
Tags drawtext

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

Related Article

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.