How to ensure that Label is within the sprite bounds?

I created a Label gave it a fontSize and added it to my Sprite in the center.
but the problem is I’m going to use the same sprite image and different Labels which means that the Label can be different text so if i use the same font size it will go out of the Sprite. How do I make sure that my Label no matter how much text it has will not go out of my sprites boundaries

Can you show a screenshot?

so you want to adjust the font size to always fall within your sprite?

In this case Settings should look like play?

No, let me give you a better screen shot.

I want that the sprite should scale appropiately not the label.

@sheshmoshen Hi, follow these steps and you should get a good result:

  1. Create the label.
  2. Create a sprite like so:
Sprite *sprite = Sprite::create();
sprite->setTextureRect(0, 0, label->getBoundingBox().size.width, 0);
  1. Add the label and another sprite (that actually has a texture) to the parent sprite.

An example:

Do I really have to use two Sprites?

You could just scale the sprite to fit the label whenever the label changes, which should be:

sprite->setScaleX(label->getContentSize().width / sprite->getContentSize().width);
label->setScaleX(1 / sprite->getScaleX());

But scaling your circular sprite might not look great. You could look into Scale9Sprite, which is designed as a sprite that you change change size without looking bad, but you’d probably need a new sprite for that.

@grimfate

This would not work, because the label would be scaled as well (if it is added as a child to the sprite).

Well can’t I add it as a child after the fact?

@crugthew this is why I have the second line which scales the label back to normal

@sheshmoshen if you are asking if you can add the label as a child after scaling the parent, a child is still affected by its parents scaling even if added after the parent is scaled. But this is why I have included the second line of code which scales the label down to counteract the parent’s scaling.

1 Like

@grimfate How about the other way, can you show me how to keep the sprite size but set the labels font size appropriately so it doesn’t go out of the sprites bounds?