I want to change text alignment from left justified to right justified in SFML. How can I do this?
// Gil text
sf::Text textGIL("Gil ", font3, 18);
textGIL.setColor(sf::Color::White);
textGIL.setString("Gil : " + to_string(Player1.gil)); //convert player1's gil to a string
window.draw(textGIL);
textGIL.setPosition(200, 310);
For clarity, I want the text to start on the right side and go left as there are more characters added to the string, rather than starting left and moving right.
sf::Text
will not handle this automatically for you. However, it does give the tools to do it. After setting the string to display, you can use getLocalBounds()
to get the bounding rect. Then you can use the width
member from this rect, and subtract that from your desired right alignment point to get the left position, which you can then pass as the x coordinate to setPosition
.
textGIL.setString("Gil : " + to_string(Player1.gil));
FloatRect bounds = textGIL.getLocalBounds();
textGIL.setPosition(200 - bounds.width, 310);
By the way, an sf::Text
object is a fairly expensive thing to make. I would not recommend constructing it on the fly every frame, but instead storing a persistent one, and calling setString
on it only when the string actually changes (although it might be optimized to not recreate the text if the string is the same, that wouldn't apply to creating a new object every frame).