Android accurately draws text locations

Source: Internet
Author: User
Tags drawtext

In android, the position of the text to be drawn using the drawText of Canvas is baseline-based. For example:

The tail of the letter Q is below the horizontal line.


<喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> VcD4KPHA + forward + z8i/tM/Cw + forward + CjxwPjxpbWcgc3JjPQ = "http://www.2cto.com/uploadfile/Collfiles/20140607/2014060709072586.jpg" alt = "\">


The key here is Paint. getTextBound. GetTextBound will fill in a Rect, which indicates the left, top, right, and bottom of a word. Note that left and top do not start from 0 to 0. Left and right should start from the 0 coordinate, while top and bottom are relative to the baseline. This information is enough for us to find the center of the text.


The last code is as follows:

@Overridepublic void onDraw(Canvas canvas) {mPaint.setTextSize(40f);mPaint.setAntiAlias(true);mPaint.setColor(0xffff0000);canvas.drawText(alphas, 30, 60, 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);mPaint.setColor(0xff000000);canvas.drawText(String.format("%d,%d,%d,%d", mBound.left,mBound.top, mBound.right,mBound.bottom), 150, y, mPaint);mPaint.setColor(0xffff0000);canvas.drawCircle(60, y, 30, mPaint);mPaint.setColor(0xffffffff);canvas.drawText(alphas, i, i+1, 60 - (mBound.right + mBound.left)/2, y - (mBound.bottom + mBound.top)/2, mPaint);mPaint.setColor(0xff000000);canvas.drawLine(30, y, 90, y, mPaint);canvas.drawLine(60, y-30, 60, y+30, mPaint);}}}

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.