Search code examples
c++sfml

How to set text origin to be the center of sf::text in SFML?


I need to center a text object in SFML to the middle of the string rather than the top left corner. Thus far, I have tried this:

topTextObj.setOrigin( (float)topTextObj.getCharacterSize() / 2, (float)topTextObj.getCharacterSize() / 2);

However, this does not fix my issue, as the text is still top-left aligned.


Solution

  • origin should be set to the center of text bounding rect:

    sf::FloatRect rc = text.getLocalBounds();
    text.setOrigin(rc.width/2, rc.height/2);