Search code examples
truetypecocos2d-js

Cocos2d-js: Custom TTF font won't display in Android


I define the font resources with

var res = {
   indieflower_ttf: {type:"font", name:"IndieFlower", srcs:["res/fonts/IndieFlower.ttf"]},
}

And create a TTF label with:

var text = cc.LabelTTF.create(text, "IndieFlower", bubble.fontsize, cc.size(60,0),cc.TEXT_ALIGNMENT_LEFT, cc.VERTICAL_TEXT_ALIGNMENT_TOP);

and will display is ok in Firefox and Chrome, but will show the default font (Arial) on Android.

What else is to do? I checked the thread Cocos2d-js: How to use a custom ttf font on android devices?, but it doesn't help.


Solution

  • The problem is, that the native platforms need the full path of the ttf font, while the html platform needs the font name. I got two solutions from the cocos2d-x forum:

    1. Use bitmap fonts. (Yes ... but I wanted to have ttf)

    2. Code it:

    In the resource file I have now:

    var res = {
        indieflower_ttf: {type:"font", name:"IndieFlower", srcs:["res/fonts/IndieFlower.ttf"]},
    }
    

    Then a helper function:

    var _b_getFontName = function(resource) {
        if (cc.sys.isNative) {
            return resource.srcs[0];
        } else {
            return resource.name;
        }
    }
    

    And to create a label:

    var text = cc.LabelTTF.create("text", _b_getFontName(res.indieflower_ttf), 48, cc.size(300,0),cc.TEXT_ALIGNMENT_CENTER, cc.VERTICAL_TEXT_ALIGNMENT_TOP);