Aligning Text

Andengine allows you to create Text and ChangeableText with different horizontal alignments, but it may not be intuitive how the alignment works. Text and ChangeableText are RectangularShape subclasses and you can think of them as text with a bounding rectangle. The text is aligned within that bounding rectangle, but the rectangle still needs to be placed correctly within the scene.

Particularly important is when you change the text in a ChangeableText object, the bounding rectangle changes size as well, but it does not change position. So your text may not be where you want it if you have aligned it in some way other than on the left. This can potentially be confusing: if you change the text, it will be anchored on the left. If you only have a single line of text it can appear as if it is always LEFT aligned, because the bounding box always contracts or expands when you change the text, but the top left corner (i.e. its position) always stays anchored.

In order to anchor a ChangeableText object either on it's center or along a Y position in the scene, you should reposition the text after changing it. Note that setPosition(x, y) always takes the upper left coordinates.

If you have a CENTER aligned ChangeableText object myText that you want to stay centered at x, y, you would use the following code:

myText.setPostion(x - myText.getWidth()/2f, y - myText.getHeight()/2f);

or, if you don't want it centered in the Y direction (i.e. it will only stay left-right centered):

myText.setPostion(x - myText.getWidth()/2f, y);

If you have a RIGHT aligned ChangeableText object myText and you want the right top corner to stay anchored at x, y, you would use the following code:

myText.setPostion(x - myText.getWidth(), y);
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License