Search code examples
c++sdl-2sdl-ttf

Is it possible to scale glyphs without having them move out of line?


I recently have been trying to implement text rendering using glyphs in my game. I have been able to render them onto the screen, but I want to be able to scale them without having them move out of the current line that is being rendered.

For example it should look like this:

Expected

Not this:

Output

In other words, I want all of the glyphs to line up along a common origin. I've tried coming up with my own algorithm using Glyph Metrics to try to place the glyphs accurately and then I multiply them by the scale. Nothing that I have tried works for every character or every scale.


Solution

  • Thank you to @Scheff for pointing me in the right direction. Using a post I found related to the one they gave to me, I was able to develop two separate formulas - one for aligning the tops of the glyphs and one for aligning the bottoms of the glyphs. I figured I'd post them here to help anybody else struggling with this problem. Here are the two functions:

    Aligning the Glyphs Along Their Tops:

    TTF_Font font;
    float scaleOfText;
    int maxY;
    int positionInput, realPositionValue; /*positionInput is where the program is told that the glyphs 
    should be rendered on the y-axis and realPositionValue is the position on the y-axis where the
    glyphs will be rendered once they are aligned*/
    char glyph;
    TTF_GlyphMetrics(font, glyph, nullptr, nullptr, nullptr, &maxY, nullptr);
        //Formula itself:
        realPositionValue = positionInput - (TTF_FontAscent(font) * scale - (maxY * scale));
    

    This looks like this: https://i.sstatic.net/pyXDy.jpg

    Aligning the Glyphs Along Their Bottoms:

    TTF_Font font;
    float scaleOfText;
    int maxY;
    int positionInput, realPositionValue; /*positionInput is where the program is told that the glyphs 
    should be rendered on the y-axis and realPositionValue is the position on the y-axis where the
    glyphs will be rendered once they are aligned*/
    char glyph;
    TTF_GlyphMetrics(font, glyph, nullptr, nullptr, nullptr, &maxY, nullptr);
        //Formula itself:
        realPositionValue = (positionInput + maxY * scale) - ((TTF_FontAscent(font) + maxY) * scale);
    

    This looks like this: https://i.sstatic.net/AswYe.jpg

    I haven't tested this with different fonts mixed together yet but I'd assume that should work just as well. I hope this helps anyone with a similar problem to the one I was facing. Thank you again everyone for helping!