Search code examples
c++texttext-renderingfreetype2

Freetype 2. Is there a way to change the size of the font in pixels after you have loaded it?


So i'm playing around with creating a simple game engine in c++. I needed to render some text so I used this tutorial (http://learnopengl.com/#!In-Practice/Text-Rendering) for guidance. It's using the library freetype 2.

Everything works great, text is rendering as it should. But now when i'm fleshing the ui out and is creating labels I would like to be able to change the size of the text. I can do so by scaling the text, but I would like to be able to do so by using pixels.

Here you can see the scaling in action:

    GLfloat xpos = x + ch.Bearing.x * scale;
    GLfloat ypos = y + linegap + (font.Characters['H'].Bearing.y - ch.Bearing.y) * scale;

    GLfloat w = ch.Size.x * scale;
    GLfloat h = ch.Size.y * scale;

So in my method renderText I just pass a scale variable and it scales the text. But I would prefer to use pixels as it is more user friendly, is there any way I could do this in freetype 2 or am I stuck with a scale variable?


Solution

  • Assuming you don't want to regenerate the glyphs at a different resolution, but instead want to specify scale as a unit of pixels instead of a ratio (i.e. you want to say scale = 14 pixels instead of scale = 29%), then you can do the following: Save the height value you passed to FT_Set_Pixel_Sizes (which is 48 in the tutorial). Now if you want a 14-pixel render, just divide 14 by that number (48), so it would be scale = 14.0f / 48.0f. That will give you the scaling needed to render at a 14-pixel scale from a font that was originally generated with a 48-pixel height.

    You might want to play with your OpenGL texture filters or mipmapping as well when you do this to improve your results. Additionally, fonts sometimes have low-resolution pixel hinting, which helps them be rendered clearly even at low resolutions; unfortunately this hinting information is lost/not used when you generate a high res texture and then scale it down to a smaller render size, so it might not look as clear as you desire.