Adding '\t' Support for SpriteFont

Jun 3, 2015 at 4:54 PM
Edited Jun 3, 2015 at 4:58 PM
I noticed that if I used '\t' in a string and try to draw it with SpriteFont, the app crashes. So, I added support for it in my own way and it works just fine. Here's how:

In the SpriteFont.cpp file, find the following method.
template<typename TAction>
void SpriteFont::Impl::ForEachGlyph(_In_z_ wchar_t const* text, TAction action)
In the case Statements, add:
    case '\t':
    {
        // Tab
        auto glyph = FindGlyph(' ');
        x += glyph->XOffset * 4;
    }
    break;
That's it. The final result should look like this:
// The core glyph layout algorithm, shared between DrawString and MeasureString.
template<typename TAction>
void SpriteFont::Impl::ForEachGlyph(_In_z_ wchar_t const* text, TAction action)
{
    float x = 0;
    float y = 0;

    for (; *text; text++)
    {
        wchar_t character = *text;

        switch (character)
        {
            case '\r':
                // Skip carriage returns.
                continue;

            case '\n':
                // New line.
                x = 0;
                y += lineSpacing;
                break;
            case '\t':
                {
                // Tab
                    auto glyph = FindGlyph(' ');
                    x += glyph->XOffset * 4;
                }
                break;
            default:
                // Output this character.
                auto glyph = FindGlyph(character);

                x += glyph->XOffset;

                if (x < 0)
                    x = 0;

                if ( !iswspace(character)
                     || ( ( glyph->Subrect.right - glyph->Subrect.left ) > 1 )
                     || ( ( glyph->Subrect.bottom - glyph->Subrect.top ) > 1 ) )
                {
                    action(glyph, x, y);
                }

                x += glyph->Subrect.right - glyph->Subrect.left + glyph->XAdvance;
                break;
        }
    }
}
Enjoy!
Coordinator
Jun 4, 2015 at 4:52 PM
You shouldn't get a 'crash' if you use an unrecognized character, but you will get an exception if you don't use SetDefaultCharacter. See the wiki page for SpriteFont.
Jun 4, 2015 at 5:25 PM
Actually, I did mean exception. Using SetDefaultCharacter will help to avoid that, but I wanted support for the tab command. Thanks for the info though, I had never set it.