FLEX拖动时复制图片
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="horizontal"
backgroundColor="#333333" xmlns:tools="tools.*" creationComplete="init();"
>
<mx:Script>
<![CDATA[
import mx.core.UIComponent;
import mx.core.DragSource;
import mx.events.DragEvent;
import mx.managers.DragManager;
[Embed(source="000.png")]
private var imgsrc:Class;
private function init():void
{
img1.source = imgsrc;
img2.source = imgsrc;
}
/**
* 开始拖拽
* */
private function dragHandler(event:MouseEvent):void
{
// 定义拖拽挂载数据源
var dsragSource = new DragSource();
// 定义拖拽图标(用于第二副图片的拖拽)
var di:Image = new Image();
// 拖拽对象
var target:Image = event.currentTarget as Image;
// 添加拖拽数据源数据
dsragSource.addData(target, "img");
dsragSource.addData(event.localX, "x");
dsragSource.addData(event.localY, "y");
// 拖拽图标
if (target.id == "img2")
di.source = new Bitmap(getBitmapData(target.content));
else
di = null;
// 执行拖拽
DragManager.doDrag(target, dsragSource, event, di);
}
/**
* 进入拖放区域
* */
private function dragEnterHandler(event:DragEvent):void
{
// 进入区域, 设置状态为允许拖放
if (event.dragSource.hasFormat("img"))
DragManager.acceptDragDrop(event.target as UIComponent);
}
/**
* 释放拖拽
* */
private function dragDropHandler(event:DragEvent):void
{
// 复制图片
var img:Image = new Image();
img.source = new Bitmap(getBitmapData(event.dragSource.dataForFormat("img") as DisplayObject));
// 处理图片防止位置
img.x = event.currentTarget.mouseX - (event.dragSource.dataForFormat("x") as Number);
img.y = event.currentTarget.mouseY - (event.dragSource.dataForFormat("y") as Number);
// 显示图片
event.currentTarget.addChild(img);
}
/**
* 获取图片信息
* */
private function getBitmapData(target:DisplayObject):BitmapData
{
var res:BitmapData = new BitmapData(target.width, target.height);
res.draw(target);
return res;
}
]]>
</mx:Script>
<mx:VBox>
<mx:Image id="img1" mouseDown="dragHandler(event);" />
<mx:Image id="img2" mouseDown="dragHandler(event);" />
<mx:Button label="Clear Images" click="testArea.removeAllChildren();" />
</mx:VBox>
<mx:Canvas id="testArea" backgroundColor="#ffffff" width="100%" height="100%"
dragEnter="dragEnterHandler(event);" dragDrop="dragDropHandler(event);" />
</mx:Application>