Formater un sf::Text

Par Thiziri (Veuillez me citer dans les sources si vous utilisez cette fonction, merci !)

Fontionne exclusivement avec la dernière révision de SFML 2.

Width & Height = Largeur & Hauteur maximum du texte graphique.

Backline = Retour à la ligne automatique.

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 : Ne pas oublier de sauvegarder une copie de votre “string” avant d'appliquer cette fonction, si vous souhaitez formater le texte en temps réel.

 
fr/sources/format_text.txt · Last modified: 2009/12/19 16:03 by thiziri
 
Recent changes RSS feed Creative Commons License Donate Powered by PHP Valid XHTML 1.0 Valid CSS Driven by DokuWiki