关于air文件拖入加载解析的两个问题

因需用到拖入加载问价解析,于是第一感觉就是想到了air,经网上查到代码如下:

public class Darg extends Sprite
    {
        public function Darg ()
        {
            if (stage) {
                creat();
            }else{
                addEventListener(Event.ADDED_TO_STAGE,creat);
            }
        }
        private var _sp:Sprite = new Sprite();
        private var _format:Array = [".jpg", ".JPG",".jpeg", ".JPEG", ".gif", ".GIF",".png",".swf",".PNG"];
        protected function creat(event:Event = null):void
        {
            _sp.graphics.beginFill(0xff0000,0.5);
            _sp.graphics.drawRect(0,0,stage.stageWidth,stage.stageHeight);
            _sp.graphics.endFill();
            addChild(_sp);
            stage.addEventListener(NativeDragEvent.NATIVE_DRAG_ENTER,ondrop);
            stage.addEventListener(NativeDragEvent.NATIVE_DRAG_DROP,ondrop);
        }
       
        private var loader:Loader = new Loader;
        protected function ondrop(event:NativeDragEvent):void
        {
            //将拖入的文件以数组形式获得,指定拖入的数据是文件数组形式
            var files:Array = event.clipboard.getData(ClipboardFormats.FILE_LIST_FORMAT) as Array;
            //获得拖入的第一个文件
            var file:File = File(files[0]);
            switch(event.type) {
                case NativeDragEvent.NATIVE_DRAG_ENTER:
                    if(_format.indexOf(file.type) != -1){
                        NativeDragManager.acceptDragDrop(this);
                    }
                    break;
                case NativeDragEvent.NATIVE_DRAG_DROP:
                    if(_format.indexOf(file.type) != -1){
                        //删除上一张加载的图片
                        loader.unload();
                        //加载拖入的图片
                        loader.load(new URLRequest(file.url));
                        removeChild(_sp);
                        addChild(loader);
                    }
                    break;
            }
        }

 

需要注意的两个问题:

1、舞台上必须有物,就是代码中为何要加个sprite的缘故;

2、必须addChild  而不能stage.addChild,即添加到当前场景上,而不是添加到底层舞台上。如果加在舞台上可以侦听到NATIVE_DRAG_ENTER 但是无 NATIVE_DRAG_DROP事件,至于具体原因没研究过了,如若有知道的,可以发表发表。

posted on 2014-06-27 14:44  L . W  阅读(248)  评论(0编辑  收藏  举报