Subscribe to GameFromScratch on YouTube Support GameFromScratch on Patreon


21. November 2014

 

In the last video tutorial we used a graphic instead of text to create a Hello World.  This is because drawing text is actually a multi step process in LibGDX and not really appropriate for a first tutorial.  It is however perfect for a second tutorial, so here we are! ;)

 

In this video we explore the difference between TTF and Bitmap fonts, show how to run the Hiero font generation tool in both Eclipse and IntelliJ IDEA then create and save a bitmap font.  We then explore the code needed to show a bitmap font on screen, including how to measure the results, apply color and text justification.

 

The video is available in up to 1080P on YouTube by clicking here.

 

The source code:

Initial Example – Loading a font and drawing text:

package com.gamefromscratch;

import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;

public class gdxtext extends ApplicationAdapter {
   SpriteBatch batch;
    BitmapFont font;

   @Override
   public void create () {
      batch = new SpriteBatch();
        font = new BitmapFont(Gdx.files.internal("Papy.fnt"));
   }

   @Override
   public void render () {
      Gdx.gl.glClearColor(0, 0, 0, 1);
      Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
      batch.begin();

        //Example One -- Drawing Text
        font.draw(batch,"Hello World",Gdx.graphics.getWidth()/2,Gdx.graphics.getHeight()/2);

        batch.end();
   }
}

 

Example 2 – Measuring and centering text:

BitmapFont.TextBounds bounds = font.getBounds("Hello World");
font.draw(batch,"Hello World",
       Gdx.graphics.getWidth()/2 - bounds.width/2,
       Gdx.graphics.getHeight()/2 + bounds.height/2);

Example 3 – Multi-line Text

String debugString = "I took one, one cause you left me\n"
           + "Two, two for my family\n"
           + "Three, three for my heartache\n"
           + "Four, four for my headaches\n"
           + "Five, five for my sorrow\n";
   BitmapFont.TextBounds bounds = font.getMultiLineBounds(debugString);

 

Example 4 -- Center justified text in the colour purple

    font.setColor(Color.PURPLE);
    font.drawMultiLine(batch,
            debugString,
            0,
            Gdx.graphics.getHeight()/2 + bounds.height/2,
            Gdx.graphics.getWidth(),
            BitmapFont.HAlignment.CENTER
            );

Programming , , ,

blog comments powered by Disqus

Month List

Popular Comments