Corona – newText positioning

Corona has great graphic handling. Making pictures and moving them on the screen is easy to and works great. When it comes to text there is a little frustration.

The API for display.newText() is:

display.newText( text, left, top, font, fontSize )

So that second and third parameter positions your text from the left and top edges. When you position with the x and y of the text object itself, you are positioning the object from the reference point which is in the center.

local myText = display.newText( "Hello World", 10, 10, "Helvetica", 24 )

The example above would place the text “Hello World” so that the upper left corner of the H would be 10 pixels right of the left edge of the screen, and 10 pixels below the top edge of the screen.

Since the reference point is in the center you can’t be sure what the x and y would be, you would have to know the width.

If you next set the x and y, as in:

myText.x = 100
myText.y = 20

You would know that that the center of the text would be at exactly 100 x and 20 y. Of course how far the left edge of the text was from the left edge of the screen would be hard to figure.

The biggest problem with with handling text in Corona, is that the reference point is reset to center when the text is redrawn. For example:

myText.text = "What!"

The text displayed is shorter and Corona reset the reference point to the center. On the screen this would look like the text were center aligned. The left and right edges would move in toward the center.

If the text is in the center there is no problem. If you have text that needs to align on the left or right, you’ll need to set the reference point and position the text anytime you change the text string it displays.

For example if you wanted to position text aligned 10 from the left edge. You could create your text field with:

local myText = display.newText( "0", 10, 10, "Helvetica", 24 )

If the text changes, imagine you have a game and this text field shows the score.

myText.text = 500

To keep the left edge 10 pixels from the left of the screen, set the reference point to the left side and then set the x position to 10.

myText:setReferencePoint( display.TopLeftReferencePoint )
myText.x = 10

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *