Finding character positions
Sunday, October 12th, 2008Also known as:
One of current projects involves some texteffects and I am loath to do anything on the timeline that can be done quicker by code. So my basic idea was (keeping the designer in me happy):
Doing the design stuff at design time on stage:
Doing the animate stuff at runtime through code:
At this point I was already thinking about converting the stage textfields to bitmaps but found I was thinking about optimising things too early, so back to KISS, basic principles first.
Silly me, I thought it would be easy in actionscript 2 to get the position of a character in a dynamic textfield. As in:
textfield.getCoordsOfChar (pIndex:Number)
but apparently no such thing exists. Ofcourse if you have a monospaced font, there are other ways to accomplish this, but this solution works for both monospaced and other fonts.
Although in actionscript 3 there is something like getCharIndexAtPoint, that is not quite what I needed.
Using a trick I managed to implement it in actionscript 2. Note that this is still under development, being researched etc, so it’s not a general I-will-work-everytime-approach. Anyway the basic principle is this:
now loop over the characters in your textfield (i = 0 to textfield.length), and:
- apply first the white textformat to everything, then applying the black textformat to the range (i, i+1)
(basically in every iteration of the loop you set everything to white except the character whose position you are looking for) - copy the textfield to the bitmap
- perform a getColorBoundsRect on the bitmap and voila an approximation of the character position
And I say approximation since it’s seems to be off by a couple of pixels, but close enough to be usuable. In addition large amounts of text will slow down the process considerably and small font sizes wreak havoc, but it’s good enough:
Download the prototype here, it includes the Greensock Tween classes, but you can use anything you like.