วิธีการนำรูปที่โหลดมาจากภายนอก Flex มาใช้ซ้ำๆได้ by Ziah
Apr0
ปกติแล้วนั้นเวลาเราทำการโหลดรูปจากไฟล์ภายนอก Flex เข้ามาใส่ Image นั้น ตัวรูปจริงๆจะอยู่ใน property ที่ชื่อว่า content ซึ่งเป็น bitmap เมื่อโหลดสำเร็จ ซึ่งถ้าเราเอาตัว content นี้ไปใช้งานเช่น นำไปใส่ container ต่างๆ จากทาง addChild ซึ่งหลังจากนี้ถ้าเรานำตัว content นี้ไปใส่ในที่อื่นๆ รูปจากที่แรกก็จะหายไป วันนี้จะมาเสนอวิธีโคลนรูปที่ได้มาจากภายนอกแบบง่ายๆกันครับ
//ในส่วนของ ActionScript
public function init():void{
var img:Image = new Image;
img.load(src); //src เป็น string ของ souce path ที่เราโหลดรูป
img.addEventListener(Event.COMPLETE,loadImgComplete);
}
public function loadImgComplete(e:Event):void{
container1.addChild(e.currentTarget.content); // container เป็นแท็ก swfLoader ด้านล่าง และ e.currentTarget มีค่าเท่ากับ img ที่โหลดมา
container2.addChild(e.currentTarget.content); // ถ้าเราทำแบบนี้ รูปจาก container ก็จะหายไปซึ่งใช้ไม่ได้
}
//ในส่วนของ mxml
<mx:SWFLoader id='container1'/>
<mx:SWFLoader id='container2'/>
//ในส่วนของ ActionScript
/* ทำการเพิ่มฟังก์ชั่นนี้เข้ามา */
public var imgBitmap:Bitmap; //สร้างตัวแปร bitmap มาเพื่อรองรับ content หลังจากโหลดเสร็จ
public function cloneBitmap(bmp:Bitmap):Bitmap{
return new Bitmap(Bitmap(bmp).bitmapData); //ทำการสร้าง bitmap ตัวใหม่มาดึงค่า bitmapData ตัวเก่ามาใส่ซึ่งก็มีค่าเท่ากับการคัดลอกข้อมูลรูปมาใส่ตัวใหม่นั่นเอง
}
public function init():void{
var img:Image = new Image;
img.load(src);
img.addEventListener(Event.COMPLETE,loadImgComplete);
}
public function loadImgComplete(e:Event):void{
imgBitmap = e.currentTarget.content; //เก็บ content ไว้ในตัวแปรที่สร้างไว้
container1.addChild(cloneBitmap(imgBitmap)); //ทำการโคลน bitmap จากตัวแปรที่ได้เก็บ content ไว้มาใส่ไว้ใน container
container2.addChild(cloneBitmap(imgBitmap)); //ทำการโคลนเช่นกันแต่นำไปไว้ใน container2
}
//ในส่วนของ mxml
<mx:SWFLoader id='container1'/>
<mx:SWFLoader id='container2'/>
เท่านี้ผลลัพธ์ของเราก็จะได้รูปภาพทั้งสองที่
Enjoy this article?
Consider subscribing to our RSS feed!
ไม่มีความเห็น
ยังไม่มีความเห็น