StyledBitmapFont

author:
Daniel Sperl
description:
Allows to colorize chars and words within a BitmapFont TextField
compatible:
v2.3
tag:
MeshStyle, color, text, bitmap fonts
homepage:
https://gist.github.com/PrimaryFeather/aae25c1d92a5a0c18d655415e1488ed2

Overview

This extension requires Starling 2.3 or the very latest head revision from GitHub.

This extension allows to colorize parts of a TextField, similar to what's possible with HTML text. Decorate the substring to be colorized with a simple XML-like syntax.

This extension consists of the class StyledBitmapFont. That's what you have to use instead of the standard BitmapFont class when instantiating the font. In the example below, the font is instantiated from two embedded files.

[Embed(source="../fonts/Ubuntu-R.png")]
private static const BmpFontTexture:Class;
 
[Embed(source="../fonts/Ubuntu-R.fnt", mimeType="application/octet-stream")]
private static const BmpFont:Class;
 
public function Demo_StyledBitmapFont()
{
    var fontTexture:Texture = Texture.fromEmbeddedAsset(BmpFontTexture);
    var fontXml:XML = XML(new BmpFont());
 
    var bitmapFont:BitmapFont = new StyledBitmapFont(fontTexture, fontXml);
    TextField.registerCompositor(bitmapFont, bitmapFont.name);
 
    var text:String = "Let's do it with {style color=#ff0000}style{/style}!"
    var textField:TextField = new TextField(700, 200, text);
    textField.format.setTo(bitmapFont.name, 30, 0x0);
    addChild(textField);
}

The color itself is assigned through tags in the following form:

{style color=#RRGGBB}text{/style}

Just like in standard XML, tags can be nested.

Unfortunately, the current version of the AssetManager does not make it easy to use this custom class instead of the standard BitmapFont class. But it's possible!

First, you need to tell it to keep the font XMLs:

assetManager.keepFontXmls = true;

When all assets are processed, create the StyledBitmapFont and let it replace the previous font.

var oldFont:BitmapFont = TextField.getBitmapFont("myFont");
var newFont:StyledBitmapFont = new StyledBitmapFont(
    oldFont.texture, assetManager.getXml("myFont"));
TextField.registerCompositor(newFont, newFont.name);

Yeah, I'd like to enhance this workflow in future Starling versions. m(

Changelog

  • 2017/11/10: First public version

Source Code

%gist(aae25c1d92a5a0c18d655415e1488ed2)%

User Comments

Feel free to edit this part of the page if you want to add information that's lacking in the above description.
Questions are better asked in the forum, though.

  extensions/styledbitmapfont.txt · Last modified: 2017/11/16 11:30 by daniel
 
Powered by DokuWiki