Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting dimensions of text in SFML

Tags:

c++

sfml

I was wondering how i get the dimensions of my text in SFML?

I tried to do it like this:

 sf::Text text("Hello SFML", font, 50);

// using text.getRect()
// i also tried getScale() & getSize()
// neither are correct

 text.setPosition( window.getSize().y/2 - text.getRect().y,50 );

Does any one know ?

Thanks :)

like image 683
Sir Avatar asked Nov 06 '12 05:11

Sir


People also ask

How do you show text in SFML?

It's very simple to use: sf::Text text; // select the font text. setFont(font); // font is a sf::Font // set the string to display text.

Does SFML have a default font?

Note that you can actually use a string without loading any font : SFML provides a default built-in one, which is Arial with a character size of 30.


1 Answers

Looking at the documentation it seems like the function getLocalBounds could be of use to you. The line would be:

float width = text.getLocalBounds().width;

I'm not sure if the sf::Text object would add any padding on the ends of the bounding rectangle.

Alternatively, you could make use of findCharacterPos with something like:

float width = text.findCharacterPos(numChars - 1).x - text.findCharacterPos(0).x;

where numChars is the number of characters in the string of your text object. However, since findCharacterPos will return global coordinates, it's probably more convenient to use getLocalBounds, this way you don't have to worry about whether your text object has any transformations applied to it.

like image 173
kevintodisco Avatar answered Nov 15 '22 18:11

kevintodisco