Search code examples
haxeopenfl

Can't use embed font


I'm doing everything just like in the instruction.

Class Fonts.hx

import flash.text.Font;

@:font("assets/fonts/OPENSANS-REGULAR_0.TTF") class OpenSansFont extends Font { }

class Fonts 
{
    public static inline var OPEN_SANS_PATH = "assets/fonts/OPENSANS-REGULAR_0.TTF";
    public static inline var OPEN_SANS_FONTNAME = "OPENSANS-REGULAR_0.TTF";

    public function new()
    {
        Font.registerFont(OpenSansFont);
    }
}

But when I try create TextFormat with this:

var tf:TextFormat;
var openSans:Font = Assets.getFont(Fonts.OPEN_SANS_PATH);
tf = new TextFormat(openSans.fontName);

I catch this error:

Assets.hx:257: [openfl.Assets] There is no Font asset with an ID of "assets/fonts/OPENSANS-REGULAR_0.TTF"

What am I doing wrong?

My project structure:

My project structure


Solution

  • You can't use openfl.Assets for Assets embedded via @:font / @:bitmap etc.

    You should use the font's name for the TextFormat constructor. I assume you've already tried that, seeing how there's an OPEN_SANS_FONTNAME variable. However, that's not the font's name, just its file name.

    On Windows, you should be able to find out the name by double-clicking on the font (right under the print / install buttons).

    Alternatively, this should work as well:

    import flash.text.Font;
    
    @:font("assets/fonts/OPENSANS-REGULAR_0.TTF") class OpenSansFont extends Font { }
    
    class Fonts 
    {
        public static var OPEN_SANS_FONTNAME;
    
        public function new()
        {
            Font.registerFont(OpenSansFont);
            OPEN_SANS_FONTNAME = new OpenSansFont().fontName;
        }
    }