This answer has been made possible thanks to @Creative Magic .
I changed the Tile from Shape to a Bitmap , which refers to a shared instance of BitmapData . This is useful because it avoids duplication of the same image data several times (once for each instance of the sprite).
When a particular fragment type is created for the first time, its raster data is generated from SVG data, which is then cached. You can change the image of a tile by simply adjusting the BitmapData link to an image of another tile:
package ; import flash.display.Bitmap; import flash.display.BitmapData; import flash.display.Sprite; import format.SVG; import openfl.Assets; // Tile is now a Bitmap class Tile extends Bitmap { // Static cache of bitmap data to avoid loading asset each time. private static var tileImageMap:Map<String, BitmapData> = new Map<String, BitmapData>(); private static var tempSprite:Sprite = new Sprite(); // Lookup cached version of tile bitmap. private static function lookupBitmapData(tile:String):BitmapData { var data:BitmapData = tileImageMap.get(tile); if (data == null) { // Render tile from SVG into temporary sprite. var svg:SVG = new SVG(Assets.getText("img/" + tile + ".svg")); tempSprite.graphics.clear(); svg.render(tempSprite.graphics, 0, 0, 56, 56); // Extract bitmap data from temporary sprite and cache. data = new BitmapData(56, 56, true, 0x00FFFFFF); data.draw(tempSprite); tileImageMap.set(tile, data); } return data; } public var tile(get,set):String; private var _tile:String; private function get_tile():String { return _tile; } private function set_tile(value:String):String { if (value != _tile) { _tile = value; // Merely adjust reference of bitmap data. bitmapData = lookupBitmapData(value); } return _tile; } public function new(tile:String) { super(); this.tile = tile; } }
source share