A small tutorial on how to load assets from .swf file with OpenFL.
First, make sure you have the latest version of Haxe and OpenFL.
You can also execute the following command to update your libs to the latest versions:
Second, make sure you have SWF Library, execute:
haxelib install swf
Now, we need to create our SWF library with all the assets.
You can do it with any version Adobe Flash or any other software of your choice.
Creat new flash project, import your assets to the library and make sure that every asset, you want to use, has AS Linkage.
In my example, I have one image with “button” class name:
You should remember class names for all the assets, you will load.
Build .swf file.
Ok, start coding.
Create new Haxe/OpenFL project with FlashDevelop (or whatever you use).
Put your .swf file into assets folder.
Open application.xml file and add the following lines:
1. our SWF Library, so we can use it:
<haxelib name=”swf” />
2. Link to our .swf file:
<library path=”assets/graphics.swf” type=”swf” />
In my case, I have graphics.swf file.
You should remember its name, as you will use it late.
Now we need to load our assets, open your .hx file, where you will load your assets (in my example, it’s Main.hx) and add the following code:
Assets.loadLibrary("graphics", onSwfLoaded); //we load our .swf file by its name "graphics"
After .swf file successfully loaded, we can start using our assets:
private function onSwfLoaded(lib:AssetLibrary):Void
var bmpd:BitmapData = null;
bmpd = Assets.getBitmapData("graphics:button"); //syntax is [SWF_FILE_NAME]:[ASSETS_CLASS_NAME]
var bmp:Bitmap = new Bitmap(bmpd, PixelSnapping.AUTO);
bmp.x = 200;
bmp.y = 100;
The same should work for MovieClips and Sounds.
Worth mentioning, SWF Library doesn’t work for HTML5 target.
In order to embed font to you project, we need to do the following steps:
1. Put all the font files into the folder within our project, for example, “assets/fonts/“;
2. Add the following line to application.xml:
<assets path=”assets/fonts” rename=”fonts” />
3. Load and use our font:
var font:Font = Assets.getFont("fonts/arial.ttf"); //load font
var format:TextFormat = new TextFormat(font.fontName, 20, 0xffffff); //create new TextFormat with our font
var text:TextField = new TextField();
text.defaultTextFormat = format;
text.embedFonts = true; //make sure we use our loaded font
text.width = 500;
text.text = "That was easy!";
text.x = 300;
text.y = 400;
If you build and run sample project, you will see the following result:
Sample project source code:
Have fun! 🙂