Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Rendering Chinese Text in LibGDX

Tech 1

LibGDX's default text rendering relies on the BitmapFont class, which uses pre-generated font atlases. The default constructor loads:

public BitmapFont() {
    this(Gdx.files.classpath("com/badlogic/gdx/utils/arial-15.fnt"),
         Gdx.files.classpath("com/badlogic/gdx/utils/arial-15.png"), false, true);
}

The FNT file defines character metrics while PNG contains glyph textures.

Font Atlas Structure

FNT files contain:

  • Metadata (face, size, Unicode stetings)
  • Character definitions (ID, position/size in atlas, offsets)
  • Kerning pairs (adjustments between specific character combinations) Example snippet:
char id=251   x=34   y=0   width=9   height=19   xoffset=1   yoffset=0   xadvance=8
kerning first=89 second=44 amount=-2

Implementing Chinese Support

Since default fonts lack CJK glyphs, generate custom font atlases:

  1. Use Hiero or similar tools:

    • Select Unicode-compatible font
    • Add required Chinese chraacters
    • Export as BMFont files (.fnt + .png)
  2. Load custom atlas:

// After placing files in assets/
BitmapFont chineseFont = new BitmapFont(
    Gdx.files.internal("custom_chinese.fnt"),
    Gdx.files.internal("custom_chinese.png"),
    false
);
  1. Render text:
SpriteBatch batch = new SpriteBatch();
// Single line
chineseFont.draw(batch, "FPS: " + Gdx.graphics.getFramesPerSecond(), 10, 30);
chineseFont.draw(batch, "祝大家光棍节快乐", 10, Gdx.graphics.getHeight()/2);

// Multi-line
String message = "第一行\n第二行";
chineseFont.drawMultiLine(batch, message, 10, 100);

Multi-line Rendering

Use overloaded methods:

// Basic multi-line
font.drawMultiLine(batch, text, x, y);

// With alignment constraints
font.drawMultiLine(batch, text, x, y, maxWidth, HAlignment.CENTER);

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.