Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multi-colored text in libgdx

Tags:

java

libgdx

I found out there is a new component in LibGDX in nightly builds - TextArea which is part of the scene2d.ui package. It's nice to have a component like this, very easy to use, but what I'm missing is some support for a multi-colored text.

I want to highlight some keywords in a text with a different color but I don't know how to do it with current api. There is one method in BitmapFontCache class:

public void setColors (Color tint, int start, int end)

Javadoc for this method says following:

Sets the color of the specified characters. This may only be called after setText(CharSequence, float, float) and is reset every time setText is called.

But I don't know how to use it through TextArea object or if it's even possible to do it that way. Someone who tried to figure it out? Every hint will be appreciated.

like image 388
jantobola Avatar asked Jan 23 '14 11:01

jantobola


2 Answers

Libgdx offers color markup, which must first be enabled on the BitmapFont with

font.getData().markupEnabled = true;

Text rendered with that font will look for color markup, where colors are surrounded in brackets. Each used color is pushed onto a stack.

  • Named colors (case sensitive): [RED]red [ORANGE]orange
  • Hex colors with optional alpha: [#FF0000]red [#FF000033]transparent
  • A set of empty brackets pops a color off the stack: [BLUE]Blue text[RED]Red text[]Blue text
  • A double bracket [[ represents an escaped bracket character, however it will not work as expected when followed by a closing bracket.

Named colors are defined in the class com.badlogic.gdx.graphics.Colors, and can be added with Colors.put("NAME", color);.

like image 57
Taylor G Avatar answered Sep 22 '22 19:09

Taylor G


Hopefully this isn't super late.

I haven't tried it your way, but I bet you would have to overwrite the setText method and then set the colors for the specific points you want. start and end are indices for the pieces of text you want in that particular color.

I have implemented a MulticolorTextArea here: https://github.com/AnEmortalKid/MulticolorTextArea/tree/mta-release

Hopefully this helps out.

like image 33
AnEmortalKid Avatar answered Sep 19 '22 19:09

AnEmortalKid