Reputation: 616
I'm currently struggling a lot with FreeTypeFontGenerator from libgdx.
Here is my code :
public class FontTestScreen extends ScreenAdapter {
private static final float WORLD_HEIGHT = 100;
private static final int FONT_SIZE = (int) (WORLD_HEIGHT/10);
private Viewport viewport;
private SpriteBatch batch;
private FreeTypeFontGenerator fontGenerator;
private BitmapFont font;
public FontTestScreen() {
fontGenerator = new FreeTypeFontGenerator(Gdx.files.internal("calibri.ttf"));
batch = new SpriteBatch();
/* Setting the viewport */
viewport = new ExtendViewport(0, WORLD_HEIGHT);
/* BitmapFont */
FreeTypeFontGenerator.FreeTypeFontParameter parameter = new FreeTypeFontGenerator.FreeTypeFontParameter();
parameter.size = FONT_SIZE;
parameter.color = Color.BLACK;
font = fontGenerator.generateFont(parameter);
}
@Override
public void resize(int width, int height) {
viewport.update(width, height, true);
batch.setProjectionMatrix(viewport.getCamera().combined);
}
@Override
public void render(float delta) {
Gdx.gl.glClearColor(1, 1, 1, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
batch.begin();
font.draw(batch, "Hello", WORLD_HEIGHT/2, WORLD_HEIGHT/2);
batch.end();
}
}
My problem is the following : If I correctly understood the viewport philosophy I should get rid of the notion of pixel. If my world has the meter for unit, well, instead of thinking with pixel I should use a viewport to set my world coordinates. In my example my world would be 100 meters high. I want to print a text whose size will be 10 meters. The problem is that the text is really pixelated and unreadable. If I change my world_height to 1000 instead of 10 and try to print my text with a size of 100 instead of 10 the text is not pixelated anymore. This behaviour doesn't happen with textures ! Why do I have to struggle with that when only the ratio should be of importance ?
The more logical answer I found is that i'm doing it wrong. So please help me understanding the correct way of dealing with fonts.
Upvotes: 3
Views: 1166
Reputation: 93591
Your viewport is in meters (or whatever) units. But FreeTypeFontGenerator uses pixels, because it's drawing pixels into a bitmap to create your font. So use the number of pixels tall you want your font to be.
In your case, since you want the font to be 1/10 the height of the screen:
private static final float FONT_SCREEN_HEIGHT_FRACTION = 1/10f;
//...
parameter.size = (int)(FONT_SCREEN_HEIGHT_FRACTION * Gdx.graphics.getHeight());
Then scale the resulting font so it will be in your world units instead of pixel units:
font = fontGenerator.generateFont(parameter);
font.getData().setScale(WORLD_HEIGHT / Gdx.graphics.getHeight());
Upvotes: 3