Welcome, Guest. Please login or register. Did you miss your activation email?

Author Topic: How to interpret the local bounds .getLocalBounds() of sf::Text?  (Read 5483 times)

0 Members and 1 Guest are viewing this topic.

MickeyKnox

  • Jr. Member
  • **
  • Posts: 53
    • View Profile
How to interpret the local bounds .getLocalBounds() of sf::Text?
« 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?
« Last Edit: November 10, 2020, 10:26:06 pm by MickeyKnox »

Laurent

  • Administrator
  • Hero Member
  • *****
  • Posts: 32498
    • View Profile
    • SFML's website
    • Email
Re: How to interpret the local bounds .getLocalBounds() of sf::Text?
« Reply #1 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.
Laurent Gomila - SFML developer

MickeyKnox

  • Jr. Member
  • **
  • Posts: 53
    • View Profile
Re: How to interpret the local bounds .getLocalBounds() of sf::Text?
« Reply #2 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?
« Last Edit: November 12, 2020, 07:25:46 pm by MickeyKnox »

Arcade

  • Full Member
  • ***
  • Posts: 230
    • View Profile
Re: How to interpret the local bounds .getLocalBounds() of sf::Text?
« Reply #3 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 and this one).

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