Flash/Flex学习笔记(11):对象拖动(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;

 
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值