SFML community forums

Help => Graphics => Topic started by: MickeyKnox on November 10, 2020, 10:19:54 pm

Title: How to interpret the local bounds .getLocalBounds() of sf::Text?
Post by: MickeyKnox on November 10, 2020, 10:19:54 pm
I'm drawing a background sf::RectangleShape for a sf::Text. After setting the Font, CharacterSize and the String I ask for its local bounds, to initialize the background rectangle:

sf::FloatRect textSize = text.getLocalBounds();
sf::RectangleShape background(sf::Vector2f(textSize.width, textSize.height));

Both the sf::Text and the sf::RectangleShape have the same position. But the background rectangle is always a little bit too small for the text. Top and Left are OK, but at the Bottom and the Right the text sticks out of the background rectangle.

Why is that so? What can I do about it?
Title: Re: How to interpret the local bounds .getLocalBounds() of sf::Text?
Post by: Laurent on November 11, 2020, 08:58:36 am
Because the text's rect also has non-zero left and top coordinates. You should adjust the position of your rectangle shape to account for that.
Title: Re: How to interpret the local bounds .getLocalBounds() of sf::Text?
Post by: MickeyKnox on November 12, 2020, 06:38:14 pm
Ok, I decided to add that portion to the background to give the text a little frame:

sf::FloatRect bounds = text.getLocalBounds();
sf::Vector2f size(bounds.left * 2 + bounds.width, bounds.top * 2 + bounds.height);
sf::RectangleShape background(size);

Just out of curiosity, what is the reason for there being a hidden offset in sf::Text?
Title: Re: How to interpret the local bounds .getLocalBounds() of sf::Text?
Post by: Arcade on November 12, 2020, 09:50:38 pm
If you search around the forums you'll find that this question comes up fairly regularly (Like this one (https://en.sfml-dev.org/forums/index.php?topic=24985.msg166440#msg166440) and this one (https://en.sfml-dev.org/forums/index.php?topic=19004.0)).

In short, text is aligned at the baseline, not the top. Different letters have different sizes, thus the offsets can change depending on which letters you are using. The space at the top matches the height of the tallest character of the font