看看这篇很棒的文章。
我对其进行了一些更改,它返回一个精灵,而不是一个。
您可以在文章中阅读更多内容,但是这个类基本上是获取资产位图数据,并将其缓存到一个对象中。每当您需要该资产的其他实例时,您都会获得缓存的位图数据。使用此技术时,您可以提高很多,将舞台质量设置为 low。
这种技术比简单地使用 cacheAsBitmap 更好,因为您可以使用 Sprite 而不是平面位图,同时仍然具有缓存的位图数据。
public class CachedSpriteFactory
{
//Declare a static data cache
protected static var cachedData:Object = {};
public static var clip:Bitmap;
public function cacheSprite(asset:Object, scale:int = 2):Sprite
{
//Check the cache to see if we've already cached this asset
var data:BitmapData = cachedData[getQualifiedClassName(asset)];
if (!data)
{
var instance:Sprite = new asset();
var bounds:Rectangle = instance.getBounds(this);
//Optionally, use a matrix to up-scale the vector asset, this way you can increase scale later and it still looks good.
var m:Matrix = new Matrix();
m.translate(-bounds.x, -bounds.y);
m.scale(scale, scale);
data = new BitmapData(bounds.width * scale, bounds.height * scale, true, 0x0);
data.draw(instance, m, null, null, null, true);
cachedData[getQualifiedClassName(asset)] = data;
}
clip = new Bitmap(data, "auto", true);
//Use the bitmap class to inversely scale, so the asset still appear to be it's normal size
clip.scaleX = clip.scaleY = 1/scale;
var sprite:Sprite = new Sprite();
sprite.addChild(clip);
//Optimize mouse children
sprite.mouseChildren = false;
return sprite;
}
}
用法:
stage.quality = StageQuality.HIGH
var cacheFactory:CachedSpriteFactory = new CachedSpriteFactory();
var coolSprite1:Sprite = cacheFactory.cacheSprite(SpriteLinkageNameInLibrary, 1);
var coolSprite2:Sprite = cacheFactory.cacheSprite(SpriteLinkageNameInLibrary, 1);
stage.quality = StageQuality.LOW