As3载入图片后全部为Bitmap,要将Bitmap的内存释放掉我们需要用到bitmapData的dispose方法,但在释放掉内存之前要做一个步骤就是将BitmapData模式保存的位图信息以2进制(ByteArray)形式保存,这样就能大大的降低内存的消耗,理想情况下是载入图片以后如果不用马上转成ByteArray,然后将位图删掉,释放内存。等到要用了再利用 byteArray.writeObject(bitmapData.getVector())方法将位图读出来,同时用byteArray.clear()方法将ByteArray的内存释放掉。放代码
package
{
import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.display.Loader;
import flash.display.Sprite;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.geom.Rectangle;
import flash.net.URLRequest;
import flash.utils.ByteArray;
public class BTB extends Sprite
{
private var data:ByteArray;
private var urlload:Loader;
private var bool:Boolean=false;
private var transBool:Boolean=false;
private var bitData:BitmapData;
private var rect:Rectangle;
private var bitMap:Bitmap;
public function BTB()
{
this.init();
}
private function init():void
{
stage.addEventListener(MouseEvent.CLICK,onClick);
}
private function onClick(e:MouseEvent):void
{
if (bool==false){
//判断未加载
loadPic();
bool=true;
}else{
if (this.transBool){
this.data=this.bitData.getPixels(this.rect);
this.removeChild(this.bitMap);
this.bitMap=null;
this.bitData.dispose();
this.data.compress();
this.transBool=false;
}else{
this.bitData=new BitmapData(this.rect.width,this.rect.height);
this.data.uncompress();
this.data.position=0;
this.bitData.setPixels(this.rect,this.data);
this.data.clear();
this.bitMap=new Bitmap(this.bitData);
this.addChild(this.bitMap);
this.transBool=true;
}
}
}
private function loadPic():void
{
var url:String="1.jpg";
var urlrequest:URLRequest=new URLRequest(url);
urlload=new Loader();
urlload.load(urlrequest);
urlload.contentLoaderInfo.addEventListener(Event.COMPLETE,onComplete);
}
private function onComplete(e:Event):void
{
var bitmap:Bitmap=e.target.content as Bitmap;
var width:Number=bitmap.width;
var height:Number=bitmap.height;
var bitmapData:BitmapData=bitmap.bitmapData;
this.rect=new Rectangle(0,0,width,height);
this.data=bitmapData.getPixels(rect);
bitmapData.dispose();
this.data.compress();
e.target.removeEventListener(Event.COMPLETE,onComplete);
trace ("complete");
}
private function clean():void
{
this.urlload.unloadAndStop(true);
this.urlload=null;
trace ("gc");
}
}
}