SFML community forums

Help => Graphics => Topic started by: Wake on January 18, 2021, 01:26:24 am

Title: Trying to use a sf::RectangleShape's Origin for the position of some text.
Post by: Wake on January 18, 2021, 01:26:24 am
Hi,

Please see the attached images below.

Image #1 shows how I set the origin of the sf::RectangleShape.
I want it to be in the dead center. So half of x & y.

Image #2 shows how I'm trying to set the position of the text to the origin of the sf::RectangleShape.

Image #3 shows that the text is nowhere near the text box. What happened?

I saw you can set an origin for the sf::Text. Should I make it half the font size for x & y? Does that even matter?

Best,
Wake
Title: Re: Trying to use a sf::RectangleShape's Origin for the position of some text.
Post by: Wake on January 18, 2021, 01:41:55 am
I got it to work in a hacky kind of way using the sf::RectangleShape's position, then offsetting it via trial and error.

I would like to learn a clean way to play text directly in the center of shapes and sprites though :)

Title: Re: Trying to use a sf::RectangleShape's Origin for the position of some text.
Post by: Hapax on January 19, 2021, 01:15:31 am
I don't know why you're using the rectangle's origin (in the rectangle's local co-ordinate system) for the text's origin (in the text's local co-ordinate system).

If you want the origin to be the centre for both, set that origin based on each object size (and position offset for text). Then, once the origins are correctly set, you can set both of their positions to the same position and they would both have their centres in the same place (they would be aligned to their centres).

For texts, use the local bounds to calculate where the local origin should be. Remember that not just the size (width and height) but the offset (left and top) should be taken into account.

To set the origin of a text to its centre:
// "text" is the text object
const sf::FloatRect textLocalBounds{ text.getLocalBounds() };
text.setOrigin({ (localBounds.left + localBounds.width) / 2.f, (localBounds.top + localBounds.height) / 2.f });
Important note: this code should be executed whenever (and after) the text string is changed and it's based on the actual text string.
(or simply executed every loop - before it is drawn)