Egret之RES资源加载
admin
2023-02-17 15:20:03
0

一 , 获取资源的3种方式:

①:RES.getRes(name:string):any

同步获取资源 这种方式只能获取已经缓存过的资源


②:RES.getResAsync(name:string,compFunc:Function,thisObject:any):void

异步获取资源,这种方式可以获取配置中含有的所有资源项。如果缓存中存在,直接调用回调函数返回,若不存在,就启动网络加载文件并解析后回调。


③:RES.getResByUrl(url:string,compFunc:Function,thisObject:any,type:string=””):void

通过url获取不在配置中的资源,通常不建议使用这个接口,只有那些不合适填写在配置中,比如获取网络上其他服务器的资源时,才采用这种方式。

    public constructor() {
        super();
        this.addEventListener(egret.Event.ADDED_TO_STAGE, this.onAddToStage, this);
    }

    private onAddToStage(event:egret.Event) {
        RES.getResByUrl('/resource/assets/bg.jpg',this.onComplete,this,RES.ResourceItem.TYPE_IMAGE);
    }

    private onComplete(event:any):void {
        var img: egret.Texture = event;
        var bitmap: egret.Bitmap = new egret.Bitmap(img);
        this.addChild(bitmap);
    }



二 , 加载资源组的步骤

1 : 加载资源配置json文件,如resouce.res.json.

RES.addEventListener( RES.ResourceEvent.CONFIG_COMPLETE, this.onConfigComplete, this ); 
RES.addEventListener( RES.ResourceEvent.CONFIG_LOAD_ERROR, this.onConfigLoadErr, this ); 
RES.loadConfig("resources/resource.res.json","resources/");

解析 :

①:RES.loadConfig

                    参数1:json配置文件的路径 。 参数2 : 子资源的位置


2: 加载json配置中的某一个资源组 , 比如加载preload资源组

private onConfigComplete(event: RES.ResourceEvent): void {
    RES.removeEventListener(RES.ResourceEvent.CONFIG_COMPLETE, this.onConfigComplete, this);
    RES.addEventListener(RES.ResourceEvent.GROUP_COMPLETE, this.onResourceLoadComplete, this);
    RES.addEventListener(RES.ResourceEvent.GROUP_LOAD_ERROR, this.onResourceLoadError, this);
    RES.addEventListener(RES.ResourceEvent.GROUP_PROGRESS, this.onResourceProgress, this);
    RES.addEventListener(RES.ResourceEvent.ITEM_LOAD_ERROR, this.onItemLoadError, this);
    RES.loadGroup("preload");
}

3:侦听加载事件:

/**
 * preload资源组加载完成
 */
private onResourceLoadComplete(event: RES.ResourceEvent) {
    if (event.groupName == "preload") {
        this.stage.removeChild(this.loadingView);
        RES.removeEventListener(RES.ResourceEvent.GROUP_COMPLETE, this.onResourceLoadComplete, this);
        RES.removeEventListener(RES.ResourceEvent.GROUP_LOAD_ERROR, this.onResourceLoadError, this);
        RES.removeEventListener(RES.ResourceEvent.GROUP_PROGRESS, this.onResourceProgress, this);
        RES.removeEventListener(RES.ResourceEvent.ITEM_LOAD_ERROR, this.onItemLoadError, this);
    }
}

/**
 * 资源组加载出错
 */
private onItemLoadError(event: RES.ResourceEvent) {
    console.warn("Url:" + event.resItem.url + " has failed to load");
}

/**
 * 资源组加载出错
 */
private onResourceLoadError(event: RES.ResourceEvent) {
    console.warn("Group:" + event.groupName + " has failed to load");
    //忽略加载失败的项目
    this.onResourceLoadComplete(event);
}

/**
 * preload资源组加载进度
 */
private onResourceProgress(event: RES.ResourceEvent) {
    if (event.groupName == "preload") {
        this.loadingView.setProgress(event.itemsLoaded, event.itemsTotal);
    }
}


三 , 自定义加载组加载资源(重点)

在json中建立资源,这次资源不放在任何组中,本人使用代码自动构建组进行加载

Egret之RES资源加载


加载管理器:

module app{
    /**
     * 构建组RES并加载
     * @author Aonaufly
     */
    export class AutoGroupResLoardManager{
        private _loaderArr : Array = null;
        private _is_loading : boolean = false;//是否正在加载中
        private static _instance : AutoGroupResLoardManager = null;
        /**当前正在加载的资源数据*/
        private _cur_data : IAutoGroupResLoarData = null;
        public static get Ins() : AutoGroupResLoardManager{
            if( AutoGroupResLoardManager._instance == null ) AutoGroupResLoardManager._instance = new AutoGroupResLoardManager();
            return AutoGroupResLoardManager._instance;
        }
        public constructor(  ){
            this._loaderArr = [];//数据加载的集合
        }

        /**
         * 开始加载接口
         * @param {app.IAutoGroupResLoarData} data
         */
        public startLoader( data : IAutoGroupResLoarData ) : void{
            if( this._is_loading ){
                this._loaderArr.push( data );//放入加载列表等待加载
            }else{
                this.createGroup2Res( data );
            }
        }

        /**
         * 构建组并加载
         * @param {app.IAutoGroupResLoarData} data
         */
        private createGroup2Res( data : IAutoGroupResLoarData ) : void{
            if( RES.createGroup( data._groupName , data._arr2Res , true )){
                this._cur_data = data;
                this.onConfigComplete(data);
            }else{
                //构建失败
                data._callBack( TypeCallBack2AutoGroupResLoar.CREATE_GROUP_ERROR );
                this.loaderNext();//继续加载下一个
            }
        }

        /**
         * 加载下一个
         */
        private loaderNext() : void{
            if( this._loaderArr.length > 0 ){
                let data : IAutoGroupResLoarData = this._loaderArr.shift();
                this.createGroup2Res( data );
            }else{
                RES.removeEventListener(RES.ResourceEvent.GROUP_COMPLETE,this.onResourceLoad, this);
                RES.removeEventListener(RES.ResourceEvent.GROUP_LOAD_ERROR,this.onResourceLoad, this);
                RES.removeEventListener(RES.ResourceEvent.GROUP_PROGRESS,this.onResourceLoad, this);
                RES.removeEventListener(RES.ResourceEvent.ITEM_LOAD_ERROR,this.onResourceLoad, this);
            }
        }

        /**
         * 添加加载侦听
         * @param {app.IAutoGroupResLoarData} data
         */
        private onConfigComplete(data : IAutoGroupResLoarData): void {
            RES.addEventListener(RES.ResourceEvent.GROUP_COMPLETE, this.onResourceLoad, this);
            RES.addEventListener(RES.ResourceEvent.GROUP_LOAD_ERROR, this.onResourceLoad, this);
            RES.addEventListener(RES.ResourceEvent.GROUP_PROGRESS, this.onResourceLoad, this);
            RES.addEventListener(RES.ResourceEvent.ITEM_LOAD_ERROR, this.onResourceLoad, this);
            RES.loadGroup(data._groupName);
        }

        /**
         * 加载侦听处理
         * @param {RES.ResourceEvent} $e
         */
        private onResourceLoad( $e : RES.ResourceEvent ):void{
            switch( $e.type ){
                case RES.ResourceEvent.GROUP_COMPLETE:
                    if( $e.groupName == this._cur_data._groupName ){
                        this._cur_data._callBack( TypeCallBack2AutoGroupResLoar.GROUP_COMPLETE , this._cur_data._class );//加载完成
                        this.loaderNext();//加载下一个
                    }
                    break;
                case RES.ResourceEvent.GROUP_LOAD_ERROR:
                    if( $e.groupName == this._cur_data._groupName ){
                        this._cur_data._callBack( TypeCallBack2AutoGroupResLoar.GROUP_COMPLETE , this._cur_data._class);//容错加载完成
                        this.loaderNext();
                    }
                    break;
                case RES.ResourceEvent.GROUP_PROGRESS://加载进度
                    if($e.groupName == this._cur_data._groupName){
                        this._cur_data._callBack( TypeCallBack2AutoGroupResLoar.GROUP_PROGRESS , this._cur_data._class ,$e );
                    }
                    break;
                case RES.ResourceEvent.ITEM_LOAD_ERROR:
                    if($e.groupName == this._cur_data._groupName){
                        this._cur_data._callBack( TypeCallBack2AutoGroupResLoar.ITEM_LOAD_ERROR , this._cur_data._class ,$e);
                        console.log("Url:" + $e.resItem.url + " has failed to load");
                    }
                    break;
            }
        }
    }

    /**
     * 自动加载数据
     * @author Aonaufly
     */
    export interface IAutoGroupResLoarData{
        /**
         * 组名
         */
        _groupName : string;
        /**
         * 资源名
         */
        _arr2Res : Array;
        /**
         * 回调方法
         */
        _callBack : Function;
        _class : any;
    }

    /**
     * 毁掉类型枚举
     */
    export enum TypeCallBack2AutoGroupResLoar{
        /**构建失败*/
        CREATE_GROUP_ERROR = 0,
        /**组加载完成*/
        GROUP_COMPLETE = 1,
        /**组加载进度*/
        GROUP_PROGRESS = 2,
        /**组中元素加载失败*/
        ITEM_LOAD_ERROR = 3
    }
}

测试调用:

module app {
   export class FntView extends eui.Component implements eui.UIComponent{
      private group_number : eui.Group;
      private img_webp : eui.Image;
      public constructor() {
         super();
         this.skinName = "resource/eui_skins/FntView.exml";
      }
      protected childrenCreated():void{
         super.childrenCreated();

         this.showNumer( 1139 );

         //this.img_webp.source = RES.getRes("bg_jpg");

            var texture:egret.Texture = RES.getRes("aab_webp");
            var result: egret.Bitmap = new egret.Bitmap();
            result.texture = texture;
            result.width = 500;
            result.height = 500;

            this.addChild(result);

            this.loaderRES();
      }




      private showNumer( num : number ) : void{
         let show : string = num.toString();
         FntManager.showFnt( this.group_number , "" , show , 125 , 75  );
      }



      ////////////////////////  RES加载器的使用
      private loaderRES():void{
         let resData : IAutoGroupResLoarData = {
            _groupName : "test2create",
            _arr2Res : [
               "c_01_jpg",
               "c_02_jpg"
            ],
            _callBack : this.callBack2Res,
            _class : this
         };
         AutoGroupResLoardManager.Ins.startLoader( resData );
      }

      private callBack2Res( type : TypeCallBack2AutoGroupResLoar , $class : FntView = null ,  $e : RES.ResourceEvent = null ) : void{
         switch ( type ){
            case TypeCallBack2AutoGroupResLoar.GROUP_COMPLETE:
                    //加载完成
                    let img01: eui.Image = new eui.Image();
                    img01.source = RES.getRes("c_01_jpg");
                    let img02: eui.Image = new eui.Image();
                    img02.source = RES.getRes("c_02_jpg");
                    img01.x = 100;
                    img01.y = 300;
                    img02.x = 300;
                    img02.y = 300;
                    $class.addChild(img01);
                    $class.addChild(img02);
               break;
            case TypeCallBack2AutoGroupResLoar.CREATE_GROUP_ERROR:
               console.error("创建组 : test2create 失败");
               break;
            case TypeCallBack2AutoGroupResLoar.GROUP_PROGRESS:
               console.log(`进度 : ${$e.itemsLoaded}/${$e.itemsTotal}`);//打印进度
               break;
            case TypeCallBack2AutoGroupResLoar.ITEM_LOAD_ERROR:
               console.log(`自定义加载组 : ${$e.groupName} , 错误单元 : ${$e.resItem.url}`);
               break;
         }
      }
   }
}

结果:

Egret之RES资源加载

控制台打印结果:

Egret之RES资源加载

上一篇:Egret之Webp

下一篇:Egret之WebStorm

相关内容

热门资讯

2026年春晚四地分会场宣布 2026年春晚四地分会场今天宣布:黑龙江哈尔滨、浙江义乌、安徽合肥、四川宜宾。
终于明白“风风棋牌是不是有挂?... 您好:风风棋牌这款游戏可以开挂,确实是有挂的,需要了解加客服微信【9784099】很多玩家在这款游戏...
【第一资讯】“秀山博胡到底是不... 网上科普关于“秀山博胡有没有挂”话题很是火热,小编也是针对秀山博胡作*弊开挂的方法以及开挂对应的知识...
【第一资讯】“旺旺冲击麻将有挂... 网上科普关于“旺旺冲击麻将有没有挂”话题很是火热,小编也是针对旺旺冲击麻将作*弊开挂的方法以及开挂对...
最新引进“新道游拼三张真的有挂... 您好:新道游拼三张这款游戏可以开挂,确实是有挂的,需要了解加客服微信【4282891】很多玩家在这款...
最新引进“暗宝透视有挂吗?”(... 有 亲,根据资深记者爆料暗宝透视是可以开挂的,确实有挂(咨询软件无需打开...
终于了解“今日长牌怎么装挂?”... 您好:今日长牌这款游戏可以开挂,确实是有挂的,需要了解加客服微信【4282891】很多玩家在这款游戏...
中天创展取得用于尾板铰耳的暗冒... 国家知识产权局信息显示,广东中天创展球铁有限公司取得一项名为“一种用于尾板铰耳的暗冒口结构”的专利,...
玩家最新攻略“麦穗有没有挂?”... 家人们!今天小编来为大家解答麦穗透视挂怎么安装这个问题咨询软件客服徽9752949的挂在哪里买很多人...
证监会科技司刘铁斌:构建规范、... 新华财经北京12月28日电(记者刘玉龙)中国证监会科技监管司副司长刘铁斌12月28日在参加中国财富管...