Search code examples
fontslibgdxthaiasianfonts

How do I properly render Thai font in libGDX?


I'm making an app to help me remember some Thai words I'm learning.

However I can't get text to render correctly.

I used this example to create a basic scene. This is what I have so far.

public class ThaiWords extends ApplicationAdapter {

    OrthographicCamera cam;
    SpriteBatch batch;
    BitmapFont thaiFont;

    @Override
    public void create () {

        FreeTypeFontGenerator generator;

        FreeTypeFontParameter parameter = new FreeTypeFontParameter();
        parameter.size = 18;
        parameter.characters = "ก";

        generator = new FreeTypeFontGenerator(Gdx.files.internal("fonts/garuda.ttf"));
        thaiFont = generator.generateFont(parameter);
        generator.dispose();

        batch = new SpriteBatch();

        cam = new OrthographicCamera();
        cam.setToOrtho(false, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
        cam.update();
    }

    @Override
    public void render () {
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

        batch.setProjectionMatrix(cam.combined);
        batch.begin();
        thaiFont.draw(batch, "ก", 0, 66);
        batch.end();
    }

    @Override
    public void resize (int width, int height) {
        cam.setToOrtho(false, width, height);
    }
}

For testing, I'd just like to display the "ก" character. The code above produces a "?" symbol.

I directly downloaded the garuda.tff font from the libGDX directory.

I'm really not sure what I'm missing! I even tried to generate a bitmap before run time but that produced a blank screen.

Any advice would be great!

edit: I've noticed on Android Studio, when I close and re-open the project the actual code changes from "ก" to "?". It may be an encoding issue but I have no idea how to fix it.


Solution

  • I would suggest you to use Stage and Label to render text.
    in create:

    Stage stage = new Stage();
    Label label = new Label("วรณ", new Label.LabelStyle(thaiFont, Color.YELLOW));
    label.setPosition(200,10);
    stage.addActor(label);
    

    and then in render method:

    stage.act(delta);
    stage.draw();
    

    I tested it and it worked just fine.

    enter image description here