一、目标
1. 在aa.swf中调用bb.swf
2. bb.swf中有一个动态文本 txt1,aa.swf调用后,更改此文本的显示内容
二、步骤
生成bb.swf文件
1.新建bb.fla,并在上面加入一个动态文本,名命为"txt1"。 txt1的初始显示为"hello"
2.Ctrl + Enter运行 bb.fla, 会生成bb.swf文件
调用bb.swf
1.新建aa.fla,在时间轴加如入代码
ch();
function ch() {
//调用swf文件部分
var lr:LoadResource = new LoadResource('bb.swf', 120, 200);
lr.addEventListener(Event.COMPLETE, cc);
addChild(lr);
//调用图片部分
//var lr:LoadResource = new LoadResource('http://img1.gtimg.com/gamezone/pics/21519/21519683.jpg', -1, -1);
//lr.addEventListener(Event.COMPLETE, cc);
//addChild(lr);
}
function cc(e:Event) {
//改变swf文件中MC对象的属性
var mc:MovieClip = MovieClip(e.target.content);
mc.txt1.text = 'bbbb';
//改变图片的显示属性
//e.target.content.height = 100;
//e.target.content.width = 100;
//e.target.content.alpha = .5;
}
说明:上面代码中将图片调用部分注释掉了,需要测试调用图片的,可自行打开
三、通用调用资源类
package {
import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.display.Loader;
import flash.display.MovieClip;
import flash.display.DisplayObject;
import flash.events.*;
import flash.net.URLRequest;
//加载资源(swf jpg png gif)
public class LoadResource extends MovieClip {
private var _url:String; //待请求的URL
private var _height:int; //MC的高度
private var _width:int; //MC的宽度
//本次加载的内容(注意: 1.要在抛出Event.COMPLETE事件后,才能使用 2.加载swf文件时,该变量是MovieClip; 加载图片时,该变量是Bitmap)
public var content:DisplayObject;
public function LoadResource(url:String, h:int, w:int) {
_url = url;
_height = h;
_width = w;
configureAssets();
}
private function configureAssets():void {
var loader:Loader = new Loader(); //此处用的是 flash.display.Loader,而不是URLLoader
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, completeHandler);
loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
var request:URLRequest = new URLRequest(_url);
loader.load(request);
addChild(loader);
}
private function completeHandler(e:Event){
content = e.target.content;
//设置返回对象的宽和高
if(_height != -1){
content.height = _height;
}
if(_width != -1){
content.width = _width;
}
dispatchEvent(e); //抛出一个”Event.COMPLETE“事件,让调用层可以做一些额外处理
}
private function ioErrorHandler(event:IOErrorEvent):void {
trace("Unable to load image: " + event.text);
}
}
}
四、其它
Loader加载过来的数据类型:
Loader 是用来代替原来MovieClip 的loadMovie 功能,用于加载外部的图片文件,SWF文件。
* 如果加载图片文件(jpg,gif,png等)时,Loader.content 得到数据类型是Bitmap 对象;
* 如果加载SWF文件(flash 9 版本)时,Loader.content 得到数据类型是MovieClip 对象;
* 如果加载SWF文件(flash 9 以前版本) 时, Loader.content 得到数据类型是AVM1Movie 对象;