How to center text?

Hello!

Is it possible to center a text object at a given x,y coordinate? The following approach does not work:

local Label = display.newText("Hello", display.stageWidth/2,display.stageHeight/2, nil, 28);
Label:setReferencePoint(display.CenterReferencePoint);

Thanks in advance for any help!

Andreas Rozek [import]uid: 4331 topic_id: 433 reply_id: 300433[/import]

Well,

I found the trick myself: simply use

local Label = display.newText("Hello", 0,0, nil, 28);
Label:setReferencePoint(display.CenterReferencePoint);
Label.x = display.stageWidth/2;
Label.y = display.stageHeight/2;

This will work as foreseen!

Kind regards,

Andreas Rozek [import]uid: 4331 topic_id: 433 reply_id: 823[/import]

Hi Andreas,

I recommend one change to your code.
Multiplication is a bit faster than division, so…

local Label = display.newText(“Hello”, 0,0, nil, 28);
Label:setReferencePoint(display.CenterReferencePoint);
Label.x = display.stageWidth*0.5;
Label.y = display.stageHeight*0.5;

May not make a big difference in this case, depends on the context and overall routines you are running.
That said, it is probably a good rule of thumb to remember.

regards,
Dave [import]uid: 3948 topic_id: 433 reply_id: 831[/import]

Dave,

you are definitely right! On a desktop, both operations should take the same time (thanks to hardware support) but on the iPhone/iPad, one should pay attention to the operations used!

Thanks for the hint!

Andreas Rozek [import]uid: 4331 topic_id: 433 reply_id: 835[/import]

You are welcome Rozek.

Sounds as though I may have only pointed out something you already understood, but perhaps this tip can help a complete beginner later. :slight_smile:

regards,
Dave [import]uid: 3948 topic_id: 433 reply_id: 851[/import]