Flex 图片拖动

图片拖动类:

package prx.drag
{
	import mx.core.UIComponent;
    import mx.core.DragSource;
    import mx.controls.Image;
    import mx.events.DragEvent;
    import mx.managers.DragManager;
    import flash.display.DisplayObject;
    import flash.display.BitmapData;
    import flash.display.Bitmap;
    import flash.events.MouseEvent;
	
	public class DragUtil
	{
		public function DragUtil() {
		}

		/**
	     * 开始拖拽
	     * */
	    public static function dragHandler(event:MouseEvent):void
	    {
	        // 定义拖拽挂载数据源
	        var dsragSource:DragSource = new DragSource();
	        // 定义拖拽图标
	        var copy:Image = new Image();
	        // 拖拽对象
	        var target:Image = event.currentTarget as Image;
	
	        // 添加拖拽数据源数据
	        dsragSource.addData(target, "img");
	        dsragSource.addData(event.localX, "x");
	        dsragSource.addData(event.localY, "y");
	
	        // 拖拽图标
	        copy.source = new Bitmap(getBitmapData(target.content));
	        // 执行拖拽
	        DragManager.doDrag(target, dsragSource, event, copy);
	    }
	    /**
	     * 进入拖放区域
	     * */
	    public static function dragEnterHandler(event:DragEvent):void
	    {
	        // 进入区域, 设置状态为允许拖放
	        if (event.dragSource.hasFormat("img"))
	            DragManager.acceptDragDrop(event.target as UIComponent);
	    }
	    /**
	     * 释放拖拽
	     * */
	    public static function dragDropHandler(event:DragEvent):void
	    {
	        var img:Image = event.dragSource.dataForFormat("img") as Image;
	        // 处理图片防止位置
	        img.x = event.currentTarget.mouseX - (event.dragSource.dataForFormat("x") as Number);
	        img.y = event.currentTarget.mouseY - (event.dragSource.dataForFormat("y") as Number);
	    }
	    /**
	     * 获取图片信息
	     * */
	    private static function getBitmapData(target:DisplayObject):BitmapData
	    {
	        var res:BitmapData = new BitmapData(target.width, target.height);
	        res.draw(target);
	        return res;
	    }
	}
}

  

 

 

使用方法:

 

<?xml version="1.0" encoding="utf-8"?>
<mx:Application 
	xmlns:mx="http://www.adobe.com/2006/mxml" 
	layout="absolute"
    width="624"
    height="458"
    minWidth="350"
    minHeight="136"
    backgroundColor="#ffffff"
	>
  	<mx:Script>
  		<![CDATA[
  			import prx.drag.DragUtil;
  		]]>
  	</mx:Script>
	<mx:Canvas id="testArea" backgroundColor="#ffffff" width="300" height="400" 
    	dragEnter="DragUtil.dragEnterHandler(event);" dragDrop="DragUtil.dragDropHandler(event);" >
		<mx:Image source="images/stop.png" mouseDown="DragUtil.dragHandler(event);" />
	    <mx:Image source="images/sound.png" mouseDown="DragUtil.dragHandler(event);" />
	</mx:Canvas>
    
</mx:Application>

 

你可能感兴趣的:(xml,Flex,Flash,Adobe)