我正在使用 SVG 图像加载我的精灵图像,以便它们可以平滑地缩放以匹配设备分辨率。目前,我天真地为每个精灵渲染 SVG 数据,但我想通过在多个精灵实例之间共享渲染图像来减少内存开销并提高性能。
如何使用 OpenFL / Haxe 实现这一点?
例如:
下面的 tile 实现是浪费的,因为 SVG 图像是在创建时为每个 tile 渲染的。
// Each of the following tile sprites contain copies of the same image.
var xyz1:Tile = new Tile("xyz");
var xyz2:Tile = new Tile("xyz");
var xyz3:Tile = new Tile("xyz");
瓷砖实施
package;
import flash.display.Shape;
import format.SVG;
import openfl.Assets;
class Tile extends Shape {
// Static cache of SVG data to avoid loading asset each time.
private static var tileImageMap:Map<String, SVG> = new Map<String, SVG>();
private static function lookupSVG(tile:String):SVG {
var svg:SVG = tileImageMap.get(tile);
if (svg == null) {
svg = new SVG(Assets.getText("img/" + tile + ".svg"));
tileImageMap.set(tile, svg);
}
return svg;
}
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;
// Render tile SVG to tile sprite.
// How can this be cached and reused by multiple tile instances?
graphics.clear();
lookupSVG(value).render(graphics, 0, 0, 56, 56);
}
return _tile;
}
public function new(tile:String) {
super();
cacheAsBitmap = true;
this.tile = tile;
}
}