-
I have a rect and a text. So, I need to put my text at center of rect. Like there:
(https://user-images.githubusercontent.com/18336087/57314294-0afd0600-70fa-11e9-850a-17c3cf89298a.png)
Now I'm using this code:
And it's drawing text from center of rect, but not on center.
sf::Vector2f centerPos = sf::Vector2f(rect1.getPosition().x + rect1.getSize().x / 2, rect1.getPosition().y + rect1.getSize().y / 2);
text1.setPosition(centerPos.x - text1.getGlobalBounds().width / 2, centerPos.y - text1.getGlobalBounds().height / 2);
-
Not sure that's what's happening because you didn't post a picture of the problem, but if the top left corner of your text is at the center of your rectangle, then it can be because you didn't set a font/string/size to your sf::Text before using its bounds. (its width and height would be 0)
-
To center text you also need to consider the local bounds' offset.
auto text = sf::Text{ "Test 1234", font };
text.setOrigin(text.getGlobalBounds().getSize() / 2.f + text.getLocalBounds().getPosition());
text.setPosition(rectangle.getPosition() + (rectangle.getSize() / 2.f));
And as G. pointed you, you of course have to first set the wanted font size and string, otherwise the calculation is off
-
Not sure that's what's happening because you didn't post a picture of the problem
Yes, you are right.
(https://i.imgur.com/JRHT07Q.png)
-
To center text you also need to consider the local bounds' offset.
auto text = sf::Text{ "Test 1234", font };
text.setOrigin(text.getGlobalBounds().getSize() / 2.f + text.getLocalBounds().getPosition());
text.setPosition(rectangle.getPosition() + (rectangle.getSize() / 2.f));
And as G. pointed you, you of course have to first set the wanted font size and string, otherwise the calculation is off
I'm creating a sf::Text object with:
sf::Font font;
font.loadFromFile("arial.ttf");
sf::Text text1("", font, 40);
I tried to use your code, but compiler gives error:
main.cpp:92:43: error: «sf::FloatRect» {aka «class sf::Rect<float>»} doesn't contain element with name «getSize»
92 | text.setOrigin(text.getGlobalBounds().getSize() / 2.f + text.getLocalBounds().getPosition());
| ^~~~~~~
main.cpp:92:83: error: «sf::FloatRect» {aka «class sf::Rect<float>»} doesn't contain element with name «getPosition»
92 | t.getGlobalBounds().getSize() / 2.f + text.getLocalBounds().getPosition());
| ^~~~~~~~~~~
-
Those functions are coming with SFML 2.6, instead you'll just have to get (left, top) for position and (width, height) for size.
-
I used:
text1.setPosition(rect1.getPosition().x + rect1.getSize().x / 2 - text1.getLocalBounds().width / 2, rect1.getPosition().y + rect1.getSize().y / 2 - text1.getLocalBounds().height / 2);
Now text is not on center of rect, but it's better, then what I had. So, I think it's normal result and I don't want to do something else with this text.