I'm trying to center some text in SFML. It doesen't really work though as you can see in the picture below.
Maybe something is wrong with my math?
void TextRenderer::renderCentered(sf::RenderWindow& window, std::string string, sf::Vector2f position, int size, sf::Color color) {
sf::Text text;
text.setFont(TextRenderer::kavoon);
text.setString(string);
float width = text.getLocalBounds().width;
text.setPosition(position.x - width / 2, position.y);
text.setCharacterSize(size);
text.setColor(color);
window.draw(text);
}
in render method:
TextRenderer::renderCentered(*window, pickuptext.str(), sf::Vector2f(player->sprite.getPosition().x, player->sprite.getPosition().y - 48), 28, sf::Color(255, 145, 61));
TextRenderer::renderCentered(*window, pickuptextdesc.str(), sf::Vector2f(player->sprite.getPosition().x, player->sprite.getPosition().y - 16), 18, sf::Color(255, 145, 61));
The formula for centering text horizontally within a bounding box is:
text_start = bounding_box_width / 2 - text_width / 2;
Looks like you may not be supplying the bounding box horizontal center point.