How to use function TextField.getCharBoundaries

April 14, 2010

Actionscript 3.0 Tutorial

Syntax:

public function getCharBoundaries(charIndex:int):Rectangle

First you have to get the position of a character in a string. e.g. “FLASH”, then “F” corresponds to 0, “L” corresponds to 1, etc. This is the parameter charIndex. You will get back the rectangle that bound the character at the location charIndex.

Limitations

  • It can only search for a single character but not a string.
  • The position of the bounding rectangle is not very exact.
  • Not work well if the string is split into 2 lines.

To solve the first problem, you can get the rectangle of the first and the last character of the string you want, then you can calculate the length of the string. So the code will be sth like this:


var rect1:Rectangle = TextField.getCharBoundaries(firstCharIndex);

var rect2:Rectangle = TextField.getCharBoundaries(firstCharIndex+StringYouWant.length-1);
// The rectangle that bound the string you want
var rect3:Rectangle = new Rectangle(rect1.x,rect1.y,rect2.x+rect2.width-rect1.x,rect1.height);

For the 2nd problem, the rectangle has about 2px of deviation from the exact location (i.e. it cannot cover the whole string completely). It would not be neat to have a little part of the string not covered by the yellow rectangle in the above example. I think this is probably due to the 2 px gutters of textfield.

To correct this in my example, I add 2 to the x,y coordinate of rect3 (as follows).

yellowRectangle.graphics.drawRect(rect3.x+2,rect3.y+2,rect3.width,rect3.height);
, , , , ,

Subscribe

Subscribe to our e-mail newsletter to receive updates.

One Response to “How to use function TextField.getCharBoundaries”

  1. Mauricio Says:

    How cooool!!! thank you very much, i just make a few changes to make it work as i needed , but….this code help me a lot! :)

Leave a Reply