Tracking the x/y position of the cursor in a TextArea
Suppose you wanted to track the position of the cursor in a TextArea. You might need to do this if you wanted to provide some contextual information to the user. And if you do so you want to position the message very near to where the user is typing.
The TextArea provides a lot of information and some of it can be used to approximate the location of the cursor but it isn’t precise. But I did happen upon an idea that gets the position of the last typed character very accurately. Check it out below:
| view source |
You should be able to see the red dot follow the cursor around. I’m doing this by checking the BitmapData of the TextArea every time the text changes. I then combine that with the BitmapData from the previous change in text and apply a Difference blend mode. You can see that in the black box at the bottom. What is different each time is the last character.
Now I can use the getColorBoundsRect method on the BitmapData to find the x/y coordinates of the last character. Actually, I have to mix in a little threshold magic because the blending doesn’t produce exactly white pixels and the getColorBoundsRect is very picky. You can check out the source code for a full explaination.
If something here has proved valuable to you then feel free to drop a couple of bucks in the tip-jar.






