SFML community forums

Help => Graphics => Topic started by: Stauricus on May 14, 2018, 01:16:27 pm

Title: positioning sf::Text
Post by: Stauricus on May 14, 2018, 01:16:27 pm
hello everybody
i want to align a text box with the bottom edge of the screen. but the way i'm doing it is not working correctly. this is a minimal code example:

#include <SFML/Graphics.hpp>

int main(){
    sf::RenderWindow window(sf::VideoMode(800, 600), "SFML window");
    sf::Font font;
    font.loadFromFile("automati.ttf");
    sf::Text text("One\nTwo\nThree\nFour", font, 30);
    text.setPosition(window.getSize().x*0.02, window.getSize().y - text.getGlobalBounds().height);
    text.setColor(sf::Color::Black);

    while (window.isOpen()){
        sf::Event event;
        while (window.pollEvent(event)){
            if (event.type == sf::Event::Closed){
                window.close();
            }
        }
        window.clear(sf::Color::White);
        window.draw(text);
        window.display();
    }

    return 0;
}

and this is the result:
(https://s7.postimg.cc/oq54tlukb/Captura_de_tela_de_2018-05-14_08-11-30.png)


i searched it, but haven't found anything about...
i'm using SFML 2.4 from the oficial Debian Testing repositories.

thanks in advance :D
Title: Re: positioning sf::Text
Post by: eXpl0it3r on May 14, 2018, 01:37:35 pm
Can you provide the values that text.getGlobalBounds() returns?
Title: Re: positioning sf::Text
Post by: Laurent on May 14, 2018, 02:01:13 pm
text.getGlobalBounds().height is not enough, you must take text.getGlobalBounds().y in account as well. Unlike other drawables, for sf::Text it is not zero (because text is aligned on the baseline, not on the top of the entity).
Title: Re: positioning sf::Text
Post by: Stauricus on May 15, 2018, 12:54:53 pm
did you mean text.getGlobalBounds().top?  ;D

thanks, it works now

#include <SFML/Graphics.hpp>

int main(){
    sf::RenderWindow window(sf::VideoMode(800, 600), "SFML window");
    sf::Font font;
    font.loadFromFile("automati.ttf");
    sf::Text text("One\nTwo\nThree\nFour", font, 30);
    text.setPosition(window.getSize().x*0.02, window.getSize().y - text.getGlobalBounds().height - text.getGlobalBounds().top);
    text.setColor(sf::Color::Black);

    while (window.isOpen()){
        sf::Event event;
        while (window.pollEvent(event)){
            if (event.type == sf::Event::Closed){
                window.close();
            }
        }
        window.clear(sf::Color::White);
        window.draw(text);
        window.display();
    }

    return 0;
}