Flash/Flex学习笔记(13):对象拖动(startDrag/stopDrag)

Flash中只有影片MovieClip(准确的讲是Sprite)可以调用startDrag,endDrag,创建对象拖动最简单的办法只要调用这二个方法即可

myobj.addEventListener(MouseEvent.MOUSE_DOWN,pickup);
myobj.addEventListener(MouseEvent.MOUSE_UP,place);

function pickup(e:MouseEvent ):void {	
	//trace("鼠标按下");	
	e.target.startDrag();	
}

function place(e:MouseEvent):void {
	//trace("鼠标抬起");	
	e.target.stopDrag();
}

其中myobj是舞台上的随便一个MovieClip实例

startDarg还能在拖动时,设定拖动的边界:

var ball:Ball=new Ball(30,Math.random()*0xffffff);

var posX:Number =  stage.stageWidth /2;
var posY:Number =  stage.stageHeight/2;
var rectSize:Number = 200;

ball.x = posX;
ball.y = posY;

addChild(ball);

ball.addEventListener(MouseEvent.MOUSE_OVER,function(){Mouse.cursor = MouseCursor.HAND });
ball.addEventListener(MouseEvent.MOUSE_OUT,function(){Mouse.cursor = MouseCursor.AUTO });
ball.addEventListener(MouseEvent.MOUSE_DOWN,MouseDownHandler);

function MouseDownHandler(e:MouseEvent) {
	stage.addEventListener(MouseEvent.MOUSE_UP, MouseUpHandler);
	//第一参数如果为true,则表示拖动时,鼠标所在点自动对齐对象中心--即所谓的锁定中心
	ball.startDrag(true,new Rectangle(posX-rectSize/2, posY-rectSize/2, rectSize, rectSize));
	//画出边界,方便更直观显示
	graphics.clear();
	graphics.lineStyle(1);
	graphics.drawRect(posX-rectSize/2, posY-rectSize/2, rectSize, rectSize);
}

function MouseUpHandler(e:MouseEvent) {
	ball.stopDrag();
}

下面再来一个稍复杂一点的示例:

R1.addEventListener(MouseEvent.MOUSE_DOWN,MouseDownHandler);
R1.addEventListener(MouseEvent.MOUSE_UP,MouseUpHandler);
R2.addEventListener(MouseEvent.MOUSE_DOWN,MouseDownHandler);
R2.addEventListener(MouseEvent.MOUSE_UP,MouseUpHandler);
R3.addEventListener(MouseEvent.MOUSE_DOWN,MouseDownHandler);
R3.addEventListener(MouseEvent.MOUSE_UP,MouseUpHandler);

//trace(numChildren);//当前舞台上的元素总数

var _originPoint:Point = new Point();

//拖动开始时
function MouseDownHandler(e:MouseEvent) {
	//trace(e);
	
	//保存原始位置(拖动完成时恢复用)	
	_originPoint.x=e.target.x;
	_originPoint.y=e.target.y;
	
	e.target.startDrag();

	setChildIndex(DisplayObject(e.target), numChildren-1);//设置拖动对象的zIndex,否则有可能在拖动过程中被其它组件挡住
	
	//拖动时显示阴影
	var _shadow:DropShadowFilter = new DropShadowFilter();
	_shadow.distance=10;
	_shadow.alpha=0.5;
	_shadow.color = 0xFFFFFF;
	e.target.filters=[_shadow];
	
	Mouse.cursor = MouseCursor.HAND;

}

//拖动完成时
function MouseUpHandler(e:MouseEvent) {
	e.target.stopDrag();
	e.target.filters=null;
	
	if (e.target.dropTarget is Shape){
		e.target.dropTarget.transform.colorTransform=e.target.transform.colorTransform; //将目标对象颜色设置为与源对象一致
	}	
	//还原初始位置
	e.target.x = _originPoint.x;
	e.target.y = _originPoint.y;
	
	Mouse.cursor = MouseCursor.ARROW;
}

 

源文件下载:http://cid-2959920b8267aaca.skydrive.live.com/self.aspx/Flash/DragObject.rar

posted @ 2010-03-16 15:11  菩提树下的杨过  阅读(6375)  评论(1编辑  收藏  举报