Friday, 2 May 2014

Libgdx - custom label text style declared in fonts.json

Here is short tutorial how set custom layout with custom font from json file.

What we need:
  1. create json file describing font style
  2. load json file to skin
  3. create own label with custom style
So let's start:

First I create font.json file to describe font style.

 {   
   com.badlogic.gdx.graphics.g2d.BitmapFont:  
   {  
     normaltext: { file: fonts64.fnt },  
     smalltext: { file: fonts32.fnt },  
   },  
   com.badlogic.gdx.graphics.Color:  
   {  
     white: { hex: "FFFFFF" },  
     green: { hex: "99CC00" },  
   },  
   com.badlogic.gdx.scenes.scene2d.ui.Label$LabelStyle:  
   {  
     default: { font: normaltext, fontColor: green},  
     smalltext: { font: smalltext, fontColor: white },  
   }  
 }  

In

 com.badlogic.gdx.graphics.g2d.BitmapFont:   
 {   
        ...  
 },   

I declare font files, as you see I use two types of fonts. You can use just one. I assume you created own fonts by program i.e bmfont and stored in "your-project/assets/data/" folder.

In

 com.badlogic.gdx.graphics.Color:   
 {   
  white: { hex: "FFFFFF" },   
  green: { hex: "99CC00" },   
 },   

I declare color which will be used.

In

 com.badlogic.gdx.scenes.scene2d.ui.Label$LabelStyle:   
 {   
  default: { font: normaltext, fontColor: green},   
  smalltext: { font: smalltext, fontColor: white },   
 }  

I declare here syles. That names will be used in java code to describe which style to use for label. I didn't add here "normaltext" because I won't use it in this example, so don't worry. When you finish your file, place it in "your-project/assets/data/" - the same place where the your .fnt file is stored.

OK, so we created file and stored in specific path. Now I need to go back to Java code. I must create skin object to load this json file.

 Skin skin = new Skin(Gdx.files.internal("data/fonts.json"));

Next step is to create label in code and use own style.

 Label instructionLabel = new Label("My instruction", skin, "smalltext");  

The third argument is the my custom style of font. If I didn't add this third element, label would load "default" style. But I want own style so I added "smalltext".

So, that's it! Don't forget add this label as "addActor(instructionLabel)" to your stage.