简体   繁体   中英

Android dynamic text drawing / touch detection

I want to display text (relatively large) and determine which character the user touches. I'd also like to embellish the text by drawing a circle (for example) over certain characters. How do I know which characters are at what location? Enforcing monospaced font would be fine if helpful programmatically.

Would it also be able to make this one line of text scroll left/right (using touch->slide) and still have touch work to determine the correct character?

A very broad question, and you've got a lot of work ahead, but here's the outline of one possible solution:

  • Create a custom view. ImageView is often a good base class to inherit.

    Override the onDraw() method of the view.

    Use canvas.drawText() to place your text on screen.

    Use paint.getTextBounds to meausure your text. See the discussion linked below for a thorough understanding. Since you drew the text on screen, and you measured it, you know exactly where each character is.

    Override the onTouch() method in your custom view and track the events you need. There are many QAs here in SO on how to do this.

    For scrolling the text, use canvas.translate() using the movement you calculate in the onTouch(). Since you know how much you scrolled (translated), you know how far your characters have moved and can offset your touch detection to detect character touches.

    Finally, since you now control all of the drawing and, your character positions are abstract, only having meaning when compared to a touch position, you can embellish them in any way choose.

Android Paint: .measureText() vs .getTextBounds()

Phew!

Good luck.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM