Last active
January 8, 2023 18:02
-
-
Save eXpl0it3r/5f43b9d9aa3f279d77ab4c84451c7241 to your computer and use it in GitHub Desktop.
How to center SFML sf::Text objects
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <SFML/Graphics.hpp> | |
int main() | |
{ | |
auto window = sf::RenderWindow{{800, 600, 32}, "SFML Window"}; | |
window.setFramerateLimit(60); | |
auto font = sf::Font{}; | |
if (!font.loadFromFile("OpenSans.ttf")) | |
{ | |
std::cerr << "Couldn't load font\n"; | |
return -1; | |
} | |
auto rectangle = sf::RectangleShape{ {300.f, 100.f} }; | |
rectangle.setOutlineThickness(1.f); | |
rectangle.setOutlineColor(sf::Color::Green); | |
rectangle.setPosition({ 200.f, 200.f }); | |
rectangle.setFillColor(sf::Color::Transparent); | |
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)); | |
auto globalBounds = text.getGlobalBounds(); | |
auto localBounds = text.getLocalBounds(); | |
std::cout << "(" << globalBounds.left << ", " << globalBounds.top << ") (" << globalBounds.width << ", " << globalBounds.height << ")\n"; | |
std::cout << "(" << localBounds.left << ", " << localBounds.top << ") (" << localBounds.width << ", " << localBounds.height << ")\n"; | |
while (window.isOpen()) | |
{ | |
for (auto event = sf::Event{}; window.pollEvent(event);) | |
{ | |
if (event.type == sf::Event::Closed) | |
{ | |
window.close(); | |
return 0; | |
} | |
} | |
window.clear(); | |
window.draw(rectangle); | |
window.draw(text); | |
window.display(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment