CVP认证学习笔记--李天宇017图片加载的进度实现
本节课的内容是实现一个进度条。与之前学习的内容有着密切的联系。首先是需要通过cc.DrawNode绘制一个节点,画一个四边形。然后通过cc.textureCache.addImageAsync实现异步加载。通过查询API,得知异步加载指定的纹理文件。如果文件图像先前没有被加载,它将创建一个新的Texture2D对象。 否则它将会在一个新线程加载纹理,加载完成时,Texture2D 对象会作为参数调用callback回调函数。回调函数将从主线程调用,所以在回调函数中可以创建任何cocos2d对象。Callback函数中首先需要再次绘制一个四边形,但是右边的两个点是变值,根据进度条的变化进行变化。部分代码如下: var HelloWorldLayer = cc.Layer.extend({ process:0, sprite:null, ctor:function () { ////////////////////////////// // 1. super init first this._super(); var size = cc.winSize; //还记得启动我们之前作业的启动画面吗 //是在main.js cc.LoadScene.preload ..... //这个文件在frameworks/cocos2d-html5/cocos2d/core/scenes/CCloaderScene.js //有兴趣可以看看引擎源码 其原理是用一个场景加载进度 var allpic=["res/bg.jpg", "res/h2.png", "res/walk01.png", "res/walk02.png", "res/walk03.png", "res/walk04.png", "res/walk05.png"]; //用一个label显示进度 // var tit=new cc.LabelTTF("当前进度0%","",50); // this.addChild(tit); // tit.setPosition(size.width/2,size.height/2); // tit.setTag(100); //使用异步任务加载所有图片,定义全局进度process for(var n=0;n<allpic.length;n++) { //异步加载图片 cc.textureCache.addImageAsync(allpic[n],this.callback,this); } var node1 = new cc.DrawNode(); var label = new cc.LabelTTF("0%","黑体",50); label.setTag(200); label.setColor(cc.color(255,255,255)); label.setPosition(size.width/2,size.height/2 + 20); this.addChild(label,2); this.addChild(node1,0); node1.setTag(100); var point1 = [cc.p(0,200), cc.p(0,300), cc.p(size.width,200)]; node1.drawPoly(point1,cc.color(0,255),5,cc.color(255,255)); return true; }, callback:function() { //每个图片加载完成都会回调 //this.process++; this.process = this.process + 1; var np=parseInt(this.process*100/5);//计算进度 //this.getChildByTag(100).setString("当前进度"+np+"%"); var point2 = [cc.p(0, cc.p(np*cc.winSize.width/100,200)]; this.getChildByTag(100).drawPoly(point2,255)); this.getChildByTag(200).setString(np+"%"); if(np==100) { //将标记为100和200的子节点移除 this.removeChild(100,true); this.removeChild(200,true); var spbg=new cc.Sprite("res/bg.jpg");//这时候就会从缓存读取 this.addChild(spbg,3); var sphero=new cc.Sprite("res/h2.png"); this.addChild(sphero,4); spbg.setPosition(cc.winSize.width/2,cc.winSize.height/2); sphero.setScale(0.3); sphero.setPosition(200,200); } } }); 最后附上作业链接: http://www.cocoscvp.com/usercode/2016_04_23/e78ffc94df5c28f28e8e699ad4e6e035c463df79/ (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |