Format a sf::Text

By Thiziri (Please mention my name in your project if you use this fonction !)

Works only with the latest release of SFML 2.

void FormatText(sf::Text &Text, int Width, int Height, bool BackLine = true)
{
    std::string String = Text.GetString();
    const sf::Font &Font = Text.GetFont();
    unsigned int CharSize = Text.GetCharacterSize();
    const int NbLinesMax = Height/CharSize;
    int LineLength = 0;
    int NbLines = 0;
    for( int k = 0; k < String.size(); k++ ) {
       if( String[k] == '\n' ) {
           NbLines++;
           LineLength = 0;
           if( NbLines > NbLinesMax ) {
                String.erase(String.begin()+k, String.end());
                break;
            }
        }
        else {
            LineLength+=sf::Text(std::string(1, String[k]), Font, CharSize).GetRect().GetSize().x;
            if( LineLength > Width ) {
                if( !BackLine ) {
                    int i = k;
                    while( 1 ) {
                        if( String[i] == '\n' ) {
                            String.erase(String.begin()+k, String.begin()+k+1);
                            k--;
                            break;
                        }
                        i++;
                    }
                }
                else {
                    int i = 1;
                    while( 1 ) {
                        if( String[k-i] == ' ' ) {
                            String[k-i] = '\n';
                            k = k-i-1;
                            break;
                        }
                        if( String[k-i] == '\n' or k == i ) {
                            String.insert(String.begin()+k, '\n');
                            k--;
                            break;
                        }
                        i++;
                    }
                }
            }
        }
    }
    Text.SetString(String);
}

PS : Don't forget to save a copy of your “string” before to apply this fonction, if you want to format the text in real time.

 
en/sources/formattext.txt · Last modified: 2009/12/19 15:58 by thiziri
 
Recent changes RSS feed Creative Commons License Donate Powered by PHP Valid XHTML 1.0 Valid CSS Driven by DokuWiki