How to accurately draw text positions on Android

Source: Internet
Author: User
Tags drawtext

The location of the DrawText drawing text using canvas in Android is based on the baseline. Such as:

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


How do you find the central position of the letter?

Let's take a look at the following example: (the number on the right, the left of the font, top, bottom)


The key to this is paint.gettextbound. Gettextbound fills a rect that represents the left, top, right, and bottom of a word. Notice that left and top are not starting from 0, 0. Left and right should start with 0 coordinates, while top and bottom are relative to the baseline. This information is enough for us to find the center of the text.


Finally, the code:

@Overridepublic void OnDraw (canvas canvas) {mpaint.settextsize (40f); Mpaint.setantialias (true); Mpaint.setcolor ( Canvas.drawtext (Alphas, 0xffff0000, 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); MP Aint.setcolor (0xff000000); Canvas.drawtext (String.Format ("%d,%d,%d,%d", Mbound.left,mbound.top, MBound.right, Mbound.bottom), Mpaint, Y, Mpaint.setcolor (0xffff0000), canvas.drawcircle (x, y, X, Mpaint), Mpaint.setcolor ( 0xFFFFFFFF); Canvas.drawtext (Alphas, I, i+1, X-(mbound.right + mbound.left)/2, Y-(mbound.bottom + mbound.top)/2, Mpain t); Mpaint.setcolor (0xff000000); Canvas.drawline ((x, y, N, y, mpaint); Canvas.drawline (y-30, X, y+30, Mpaint);}}

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.