Dynamic text button


#1

Hi,
What is the workaround to create 3 buttons with the same design but different texts (short text, medium length text, long text)?
a) do I need 3 different images as a background ? What if i don’t know the length of the text ?
b) or I can use a single image and shrink/stretch it horizontally/vertically somehow when a text needs more/less space to fit in?

I hope i don’t need hundreds of images for each button :slight_smile:

I’m just a beginner. What is the best practice ?


#2

Proper way: 9-Slice, you probably need to use some plug-in


#3

No, you do not need to have many different images for one button.

Usually, I create a button using:
buttonNext = this.game.add.button(x, y, spriteName, optionalFrameNumber);
buttonNext.anchor.setTo(0.5);
and create a text using:
textNext = this.game.add.text(buttonNext.x, buttonNext.y, ‘Next’, fontStyle);
textNext.anchor.setTo(0.5);

Then, to make the button fit the text:
buttonNext.scale.setTo(textNext.width / buttonNext.width, 1);
^ this will give you different sized buttons

Similarly, if you want to make the text fit the button instead:
textNext.scale.setTo(buttonNext.width / textNext.width, 1);
^ this will give you same sized buttons with different text sizes

If you need this button to have be more interactive (i.e. enlarges when mouse hovers over button) it would be good to group the button and text into one group so that the text will enlarge with the button, making it seem like the text is in the button itself.
This way, you can reuse your button object and just change the text every time.

Hopefully this will help you! :sunny: