Categories
Haxe Openfl

Using svg for assets in Openfl

I wanted to use svg for icons in an Openfl project.
It’s not intuitive to do this, so I wrote it down for future use.

What are svg files?

Scalable Vector Graphics (SVG) is an XML-based vector image format for two-dimensional graphics with support for interactivity and animation.

Source: http://en.wikipedia.org/wiki/Scalable_Vector_Graphics

Good to remember that they scale awesomely without lost of resolution!

How to add it to your project

You can find the svg code on github.
But you can install it easier with haxelib

Open your terminal and write:

haxelib install svg

To add it to an OpenFL project, add this to your project file:

<haxelib name="svg" />

Code

import openfl.Assets;
import openfl.display.Shape;
import openfl.display.Sprite;
import format.SVG;
 
class SVGExample extends Sprite
{

  public function new()
  {
    var svg : SVG = new SVG(Assets.getText("assets/openfl.svg"));
    var shape : Shape  = new Shape();
    svg.render(shape.graphics);
    addChild(shape);
  }
}

NICE!!!
But now the cool part: it scales without losing resolution

Check the highlighted line for the changes,

import openfl.Assets;
import openfl.display.Shape;
import openfl.display.Sprite;
import format.SVG;
 
class SVGExample extends Sprite
{

  public function new()
  {
    var svg : SVG = new SVG(Assets.getText("assets/openfl.svg"));
    var shape : Shape  = new Shape();
    svg.render(shape.graphics,0,0,1000,1000);
    addChild(shape);
  }
}

for the curious: https://github.com/openfl/svg/blob/master/format/SVG.hx

Sources

  • I remembered this gist, which explains almost everything.
  • Get icons here, they are free for download as long as you credit freepik
  • Featured image from webdesignerdepot

2 replies on “Using svg for assets in Openfl”

tried your method but getting this:
Unknown identifier : addChild

Any idea why I would be getting this error?

Comments are closed.