libgdxalphamarkupbitmap-fonts

LibGDX BitmapFont Markup Alpha Value


Alright, so I have a bitmap font with markup enabled. The problem is, I need to set the global alpha value for a whole string of text without setting an individual alpha value for each color code.

For example, I have...

"[#0000ff]this is blue, [#990000]this is red"

I'd like the font text to fade into the background by setting an alpha value. Is there any way to do this without manually parsing color codes and sticking an alpha value into the brackets?

I've also tried adding custom colors with Colors.put(..), but that gets really clunky, as I have to set the alpha value to each color I'm using, with each line of text that I am drawing.


Solution

  • You'll need to use the BitmapFontCache class.

    So for example, say your code currently looks like this...

        font.drawWrapped(batch, text, x, y, wrapWidth, alignment);
    

    Replace it with the following and you can control the alpha in the way you require...

        BitmapFontCache cache = font.getCache();
        cache.clear();
        TextBounds bounds = cache.addMultiLineText(text, x, y, wrapWidth, alignment);
    
        // This is the useful bit!
        cache.setAlphas(alphaTransparency); 
    
        cache.draw(batch);
    

    Note - If you're using distance field fonts then the shader most people use for them doesn't support alpha, but it's easy to fix it so it does. Let me know if you hit that problem.