问题: list里面的对象怎样拖到画面里?
思路 把list里的对象直接拖到画面里的功能,在场景编辑器里常常用到,我们会放一个List,里面每一项对应一个建筑物,用户可以把建筑物拖拽到场景中。这也和flash的元件库拖拽东西到舞台是一样的效果。 我们可以在List的每一项中存储该项所对应的ClassName,当拖拽开始时,创建对应的实例,并让它跟随鼠标。直到在画面有效区域中松开鼠标才将其添加到新的DisplayObjectContainer内。
具体的我写了一个演示,右侧是List,请从里面把内容拖到左侧的框框里放下看效果。点击此处下载源文件。
Document Class :
package org.mousebomb.dragLiToCanvas
{
import fl.events.ListEvent;
import fl.controls.List;
import fl.data.DataProvider;
import flash.display.Sprite;
import flash.events.MouseEvent;
import flash.geom.Point;
import flash.utils.getDefinitionByName;
/**
* @author Mousebomb (mousebomb@gmail.com)
* @date 2010-4-27
*/
public class DragListItemToCanvas extends Sprite
{
public var list : List;
public var canvas : Sprite;
private var isHoverLi : Boolean = false;
private var curHoverLi : Object ;
public function DragListItemToCanvas()
{
//如果不写下面这一行,flash不会将此类编译进去,运行时会报错
Class1;
Class2;
//创建list的内容
list.dataProvider = new DataProvider();
list.addItem({label:”有胆你就拖拽我”, data:”org.mousebomb.dragLiToCanvas.Class1”});
list.addItem({label:”我和楼上一样”, data:”org.mousebomb.dragLiToCanvas.Class2”});
list.addEventListener(MouseEvent.MOUSE_DOWN, onMouseDownH);
list.addEventListener(ListEvent.ITEM_ROLL_OVER, onHoverLi);
list.addEventListener(ListEvent.ITEM_ROLL_OUT, onOutLi);
stage.addEventListener(MouseEvent.MOUSE_UP, onMouseUpH);
}
private function onOutLi(event : ListEvent) : void
{
isHoverLi = false;
curHoverLi = null;
}
private function onHoverLi(event : ListEvent) : void
{
isHoverLi = true;
curHoverLi = event.item;
}
//松开鼠标
private function onMouseUpH(event : MouseEvent) : void
{
//有拖拽物体
if(curDraging)
{
curDraging.stopDrag();
removeChild(curDraging);
//在canvas上着陆
if(canvas.hitTestPoint(event.stageX, event.stageY))
{
canvas.addChild(curDraging);
curDraging.alpha = 1;
var localPos : Point = canvas.globalToLocal(new Point(event.stageX, event.stageY));
curDraging.x = localPos.x;
curDraging.y = localPos.y;
}
curDraging = null;
}
}
//记录当前拖拽
private var curDraging : Sprite;
private function onMouseDownH(event : MouseEvent) : void
{
if(curHoverLi)
{
var className : String = curHoverLi[“data”];
curDraging = getItemByClassName(className);
curDraging.x = event.stageX;
curDraging.y = event.stageY;
curDraging.alpha = .6;
addChild(curDraging);
curDraging.startDrag();
}
}
//获取对应的实例
private function getItemByClassName(className : String) : Sprite
{
var cla : Class = getDefinitionByName(className) as Class;
return new cla();
}
}
}
技术内容转载请注明来源,个人日记不允许转载,欢迎指出任何有错误或不够清晰的表达。可以邮件至 mousebomb@gmail.com