我正在尝试复制位图数据的像素。但我一直收到以下错误
Parameter sourceBitmapData must be non-null.
它发生在方法drawImage中。在我的跟踪之后说“获得画布数据”。
canvasData.copyPixels(image,tileRect,tilePoint);
以下是我的代码
package com.objects {
import flash.display.Sprite;
import flash.display.BitmapData;
import flash.display.Bitmap;
import flash.geom.Point;
import flash.geom.Rectangle;
import flash.display.Loader;
import flash.net.URLRequest;
import flash.net.*;
import flash.events.*;
import flash.display.LoaderInfo;
public class gameObject extends Sprite {
protected var goWidth:Number;
protected var goHeight:Number;
protected var image:BitmapData;
protected var canvas:Bitmap;
public function gameObject():void
{
init();
}
private function init():void
{
}
public function loadImage(imageDir:String):void
{
trace("loadimage");
var loader:Loader = new Loader();
loader.contentLoaderInfo.addEventListener(Event.COMPLETE,imageComplete);
loader.load(new URLRequest(imageDir));
}
private function imageComplete(e:Event):void {
var loader:LoaderInfo = LoaderInfo(e.target);
image = Bitmap(loader.content).bitmapData;
trace("imagecomplete");
}
public function drawImage(xPoint:Number = 0, yPoint:Number = 0, tWidth:Number = 0, tHeight:Number = 0):void
{
var tilePoint:Point = new Point(0,0);
var tileRect = new Rectangle(xPoint,yPoint,tWidth,tHeight);
var canvasData:BitmapData = new BitmapData(tWidth,tHeight);
trace("got canvas data");
canvasData.copyPixels(image,tileRect,tilePoint);
trace("copied pixels");
canvas = new Bitmap(canvasData);
}
}
}
以下是我用来调用类
的内容balls = new Array();
balls[0] = new gameObject();
balls[0].loadImage("com/images/ball.gif");
balls[0].drawImage(0,0,15,15);
任何人都有线索?
答案 0 :(得分:2)
发生错误是因为image
变量(copyPixels
的第一个参数)为空。
image
GameObject
变量填充在仅在加载完成时调用的imageComplete
方法中。 loader.load()
是异步的,在图像完全加载之前返回。您drawImage
返回后立即调用loadImage
(),因此image
此时将为空。从complete
方法发送imageComplete
个活动,并在致电drawImage
之前等待。
private function imageComplete(e:Event):void
{
var loader:LoaderInfo = LoaderInfo(e.target);
image = Bitmap(loader.content).bitmapData;
trace("imagecomplete");
//dispatch a complete event.
dispatchEvent(e);
}
game = new GameObject();
//listen for the complete event
game.addEventListener(Event.COMPLETE, handleComplete);
game.loadImage("com/images/ball.gif");
private function handleComplete(e:Event):void
{
//load complete and image populated : draw the image.
var game:GameObject = GameObject(e.target);
game.drawImage(0,0,15,15);
}