My favorites | Sign in
Project Home Downloads Wiki Issues Source
Search
for
addingText2D  
How to add text to 2D graphics
Updated Feb 17, 2012 by christop...@gmail.com

How to add text to 2D graphics

The Font class is no longer in libGDX and BitmapFont class is now in force.

Sample code from SVN:

 !TextureAtlas textureAtlas = new !TextureAtlas("data/main");
 font = new !BitmapFont(Gdx.files.internal("data/calibri.fnt"),
         textureAtlas.findRegion("calibri"), false);

Q: How can i write some text? Do I need font.png and font.fnt?

A: There is an embedded font "arial-15", so you can directly write using a BitmapFont. For custom text instantiate a BitmapFont, and use

 font.draw(spritebatch, "my-string", x, y);
 

A: you need a .png file containing every symbol you need your font to contain (e.g. alphanumeric characters). The .fnt file houses the locations of every character in the .png file.

One of the simplest ways to procure these files is through a piece of software called Hiero, which generates bitmap fonts of multiple sizes and styles based on your computer's TTF fonts.

A nice tutorial for the user-interface can be found here

Adding fonts to a project's directory

Once you have made all the fonts you need, you need to add them to your project's /data folder.

Adding fonts to a project

Creating your objects

At minimum, you need to declare two objects: a SpriteBatch to extract the characters from the .png file and your BitmapFont object.

SpriteBatch spriteBatch;
 BitmapFont font;
 CharSequence str = "Hello World!"

BitmapFonts can only draw text using CharSequence objects, so I'm providing one in the example.

Using the font files in your code

It's best practice to use Gdx.files.internal(Str relativePath) to retrieve your .png and .fnt files.

spriteBatch = new SpriteBatch();
 font = new BitmapFont(Gdx.files.internal("data/nameOfFont.fnt"),
         Gdx.files.internal("data/nameOfFont.png"), false);

The first line in the example simply instantiates a new SpriteBatch, which you can learn about elsewhere in this wiki (TODO: link to SpriteBatch tutorial and/or API doc).

The second line instantiates our font.

  • The first argument passed is a function call to Gdx.files.internal() which returns a FileHandle object containing the .fnt file you added to your project.
  • The second argument passed is another call to Gdx.files.internal() which returns yet another FileHandle object, this time containing the .png file storing all your font characters.
  • The final argument is a boolean which indicates whether characters the font object draws will be flipped on the y-axis, appearing upside down. I'm setting this to false for the time being, but I'm sure there are instances where someone would want to set this boolean variable to true as well.

[TODO: provide examples for each constructor method in the API docs]

Writing text on the screen

Text is written on-screen in the class's draw method, but the SpriteBatch object must be called first.

spriteBatch.begin();
 font.setColor(1.0f, 1.0f, 1.0f, 1.0f);
 font.draw(spriteBatch, str, 25, 160);
 spriteBatch.end();

The first and last lines in the code are essential, without which you will generate lots of errors. What you really should be concerned with are the font.setColor() and font.draw() commands.

font.setColor() is used here as a precautionary measure. Hypothetically speaking, if the characters in your font's .png file are colored black and your screen's background is also colored black, you will never see your text when it is drawn. font.setColor() can change the color of your font to anything within the visible spectrum, and can even take an alpha variable if you want to add transparency to it.

font.draw() is where everything happens: The first argument passed is the SpriteBatch object. The second argument passed is the CharSquence object we defined at the beginning of this example. The third and fourth arguments are ints in the x and y position, respectively - in integer values - that indicate the text's starting position.

Text Color

There are several methods included in the BitmapFont class that allow you to format your text.

 font.setColor(0.0f, 0.0f, 1.0f, 1.0f); // tint font blue
 spriteBatch.begin();
 font.draw(spriteBatch, charSeq, xPos, yPos);
 spriteBatch.end();
 

TODO: write about scaling fonts to different sizes.

String builder

Another approach is to have the text made up from bitmaps as described in this String builder tutorial:

http://code.google.com/p/libgdx/wiki/StringBuilder

Comment by project member radiok...@gmx.de, Sep 13, 2011

Hi Christopher, try suppressing those "?" after CamelCaseWords? by adding a "!" just before them. ;-)

Comment by cloudju...@gmail.com, Nov 2, 2011

Hi guys, absolutely loving libgdx - I was wondering tho, whether there is somewhere or there will be something about resizing the fonts so that they are drawn exactly to the size I want? Thanks a lot!

Comment by project member christop...@gmail.com, Jan 16, 2012

>I was wondering tho, whether there is somewhere or there will be something about resizing the fonts so that they are drawn exactly to the size I want? Thanks a lot!

I am somewhat against resizing fonts, not from an engineering standpoint but from a graphic design standpoint. Fonts do not scale nicely. Scaling a size 16 font by 1.5 is not the same as using separate 16 and 24 sizes of the same font. It's because the proportions of each symbol's curves, serifs, and lengths/widths will not scale properly. I wish I could draw a picture of what I am trying to discuss here.

Anybody is free to add/subtract to/from this article. I don't claim exclusivity on it. And... ::looks at article:: I just noticed I was planning on writing something about it, or at least thought it deserved a closer look. I had a difficult time knowing when to use it in the SpriteBatch/Font lifecycle.

Comment by project member kalle.ha...@gmail.com, Jan 30, 2012

I fixed mistakes with sprite batch coloring. You can set it freely inside of sprite batch and you dont have to create multiple fonts. Checked the actual code and tested it.

Comment by belli...@gmail.com, Feb 3, 2012

This tutorial was really helpful however I am having an issue. I have an OrthographicCamera? set to x:20, y:12 where I draw my game (between 0-20x and 0-12y). When I draw font at 9,9, it is massive on my game (as it's drawing in 15pt). I can't scale less than.15f or the font disappears and its still way too big. Is there a good way to reduce this font size?

Comment by project member treyy...@gmail.com, Feb 16, 2012

bellindj:

You will probably want to use a different camera for the font drawing, one pixel-perfect or close to it. That way you won't need to scale the font.

Comment by thecto.d...@gmail.com, Mar 3, 2012

how do you open other formats , that use vectors instead of bitmaps for the characters ? is there any tutorial for that? does libgdx even support it?

Comment by dunatv@gmail.com, Mar 10, 2012

SpriteFont? from http://www.nubik.com/SpriteFont/ has more features than Hiero. And it saves the font to .xml and .png. Seriously Hiero is old fasion.

Comment by spaa...@gmail.com, Apr 30, 2012

I had problems making this work, after few frustrating hours i can share these tips:

best program to make .fnt and .png is http://www.angelcode.com/products/bmfont/ (in export settings: set colors to 32bit; "white text with alpha"; width and height big enough to hold all chars in single file )

don't forget to .enableBlending() on SpriteBatch.

Comment by mkfr...@gmail.com, Jul 9, 2012

How can we make the text rotate to vertical?

Comment by lemon...@gmail.com, Nov 4, 2012

I have found creating new BitmapFonts? to be very expensive due to loading the image. My solution is this:

public static BitmapFont? staticFont;
public static BitmapFont? createDefaultFont() {
return new BitmapFont?(staticFont.getData(), staticFont.getRegion(), false);
}
Comment by Crazyboy...@gmail.com, Jan 21, 2013

How to make multiresolution text for another imported font ?


Sign in to add a comment
Powered by Google Project Hosting