假设我有一个名为 Icon 的空类,在运行时我想
将其图像更改为某物
在编写代码之前,请确保您按照这些示例步骤进行了准备...
1) 打开Library (ctrl+L),右键选择MovieClip类型的“create new symbol”,命名为Icon,然后查看高级标签在下方...
2) 勾选名为“Export For ActionScript”的框,该框会自动填充名为 Class 的框,其中包含 Icon 文字。点击确定,您就准备好了。
3) 将一个或两个图像添加到库中,然后右键单击选择“属性”,然后再次像 链接 部分中的步骤 (2) 一样勾选“导出为 AS”选项并给出您希望稍后通过代码键入的名称。我们假设您选择了 Pic1 和 Pic2 等名称。还要注意这些位图的“基类”是bitmapData?这就是您更改的数据以通过代码更新图像。
所以要通过代码动态更新...创建一个位图并使用库中的任何 bitmapData 更新其像素数据。比如:
//# in your imports...
import flash.display.MovieClip;
import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.utils.getQualifiedClassName;
import flash.utils.*;
....
//# in vars declarations...
public var my_icon : Icon = new Icon ();
public var my_BMP : Bitmap;
public var str_Type : String = ""; //later holds library object type for checks
....
//# later in your code
stage.addChild(my_icon); //looks invisible since empty
my_BMP = new Bitmap; //create new instance
my_icon.addChild ( my_BMP ); //add the empty bitmap into Icon
change_Icon ( Pic1 ); //parameter can be Library's Bitmap or Movieclip
制作change_Icon 函数...
如果您只是保留位图(PNG 文件?),您可以使用这样的简单函数...
public function change_Icon ( in_Param : Class ) : void
{
my_BMP.bitmapData = new in_Param as BitmapData; //replace pixels of existing bitmap container
}
但既然你说它可以是任何东西,有时是位图,有时是影片剪辑,那么在这种情况下你必须检查输入并相应地处理。
public function change_Icon ( in_Param : * ) : void
{
//# Check the input type and handle it
str_Type = String ( getDefinitionByName( String( getQualifiedSuperclassName(in_Param) ) ) );
if ( str_Type == "[class BitmapData]" )
{
trace ( "this object is a Bitmap..." );
my_BMP.bitmapData = new in_Param as BitmapData; //replace pixels of existing bitmap container
}
if ( str_Type == "[class MovieClip]" )
{
trace ( "this object is a Movieclip..." );
var temp_MC = new in_Param();
var temp_BMD : BitmapData = new BitmapData( temp_MC.width, temp_MC.height );
my_BMP.bitmapData = temp_BMD; //assign data to this bitmap
temp_BMD.draw (temp_MC); //update by drawing
}
}