Welcome, Guest. Please login or register. Did you miss your activation email?

Author Topic: I want to fit a text inside a box  (Read 4212 times)

0 Members and 1 Guest are viewing this topic.

iride

  • Jr. Member
  • **
  • Posts: 88
    • View Profile
    • Email
I want to fit a text inside a box
« on: March 28, 2016, 07:37:43 am »
I'd like to make a textbox using sf::RectangleShape and sf::Text.
Rectangle has a fixed height.
My question is how to find the perfect character size and text position to fit the text in rectangleshape?

Ixrec

  • Hero Member
  • *****
  • Posts: 1241
    • View Profile
    • Email
Re: I want to fit a text inside a box
« Reply #1 on: March 28, 2016, 03:14:10 pm »
Because text is extremely complicated, there is no perfect answer to this question, but without writing an essay about descenders and base lines and other stuff you probably don't care about...

As far as I know, in SFML there's simply no way to go from a desired pixel width/height to its closest characterSize. I believe this is because fonts are simply too complicated for such a thing to be possible in the first place, but someone else will have to confirm that. So you're going to have to write some "guess and check" code.

I can think of three parts of the SFML API that you can play the guess and check game with: First, sf::Font::getLineSpacing(), which is probably the simplest option if you mostly care about the height. Second, sf::Text has getLocalBounds() and getGlobalBounds() methods. Third, you could use sf::Font::getGlyph() to get the bounding rectangles for every glyph in your string and add up their widths and heights.
« Last Edit: March 28, 2016, 03:16:33 pm by Ixrec »

 

anything