Centering Text

Hey guys,

So, I’m trying to show the player’s score after you die, but I have one problem… My text won’t center…

For example, a player scores “100” I have an image that says “score” and then shows the score under it…

but, if a player scores “1000” my text will be off-center because of the extra digit…

So, I was just wondering. Is there a command to start text in the center? [import]uid: 95032 topic_id: 29283 reply_id: 329283[/import]

One solution is to format your text with the predetermined maximum number of digits.

Ie say your score can go no more than 6 digits (max score available is 999999)

Example: (copy + paste into a main.lua file to see it in action)

local score = 1000  
local scoreLabel = string.format( "%06d", score )  
  
local scoreText = display.newText( scoreLabel, 0, 0, native.systemFont, 18 ) -- Will display 001000  
scoreText.x, scoreText.y = display.contentCenterX, 25  
  
--Update the text when needed  
local function updateScore()  
 score = score + 5000   
 scoreText.text = string.format( "%06d", score )  
end  
  
timer.performWithDelay( 500, updateScore, 0 )  

[import]uid: 84637 topic_id: 29283 reply_id: 117749[/import]

another solution is to use the ui.newLabel class

local ui=require("ui")  
local label=ui.newLabel{font=native.systemFont,size=18,align="center",textColor={255,255,255,255},text="initial score",bounds={15,100,290,20}}  

where the x and w values of the bounds parameter are chosen so that x+w/2=xc
in the example above, since 15+290/2=160 the text will be centered at 160 pixels from the left end
you can use label:setText(score) to change the score afterwards
[import]uid: 6459 topic_id: 29283 reply_id: 117778[/import]