Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to center a sf::Text in a sf::RectangleShape

Is there a easy way to center an sf::Text object in an sf::RectangleShape object?

The text has variable lengths, but isn't changing after creation.

I'm using SFML 2.4.

like image 573
Profilüfter Avatar asked Jan 02 '26 00:01

Profilüfter


1 Answers

Centering one object over the other is usually a trivial task: Just determine the size difference between the objects and use it as an offset by dividing it by 2.

However, once you use (True Type) font rendering, things become a tiny bit more tricky, because the origin of these font glyphs isn't necessarily on the top left of the actual glyph. It might be anywhere, depending on the font and the character/glyph to be rendered (serifs and other decoration elements are a typical example for this).

Getting back to the basic formula:

offset = (shape.size() - text.size()) / 2

Now let's add the text offset:

offset = (shape.size() - text.size()) / 2 - text.offset()

There are multiple ways to do this using SFML. Personally I'd probably create my custom sf::Drawable derived class drawing both the box and the text.

For standalone drawing (like you do), I actually prefer setting the text's origin to account for the offset. This way you're able to set both shape and text's position identically and they'll be perfectly aligned without touching the origin/offset again (unless you change the text).

const sf::FloatRect bounds(text.getLocalBounds());
const sf::Vector2f box(shape.getSize());
text.setOrigin((bounds.width - box.x) / 2 + bounds.left, (bounds.height - box.y) / 2 + bounds.top);

Note that I've basically swapped operands since I'm setting the origin rather than offset. For example, to move the text 5 units to the right, I have to set the origin to -5 rather than 5.

The constant is really just there to make the whole line a bit more readable. You could also do everything inline, but I prefer the cleaner way.

Here's the whole thing in action using Arial and Lucida Handwriting:

Example Screenshot

Note how "Hello World" is aligned differently depending on whether the font glyphs take more space downwards. If you don't want that behavior, you'd have to use some fixed line height rather than relying on the height of the sf::Text object.

like image 124
Mario Avatar answered Jan 03 '26 14:01

Mario



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!