我目前是这样想的(以下代码仅提供思路,未测试):
RemoteImageLoader.js:
cc.Class({
extends: cc.Component,
properties: {
lockSize: false
},
onLoad: function() {
this._mySpriteFrame = null;
},
_releaseMySpriteFrame: function() {
// 若为原生环境,且mySpriteFrame存在,则release
if (CC_JSB && this._mySpriteFrame) {
this._mySpriteFrame.release();
this._mySpriteFrame = null;
}
},
_setMySpriteFrame: function(spriteFrame) {
// 仅在原生环境下需要retain, release
if (CC_JSB) {
spriteFrame.retain();
this._releaseMySpriteFrame();
this._mySpriteFrame = spriteFrame;
}
},
_createSpriteFrameWithoutWarning: function() {
// 临时屏蔽创建cc.SpriteFrame时来自引擎的BS
var warn = cc.warn;
cc.warn = function() {
};
var spriteFrame = new cc.SpriteFrame();
// 恢复cc.warn
cc.warn = warn;
return spriteFrame;
},
_setTexture: function(texture) {
// 创建cc.SpriteFrame,屏蔽warning
var spriteFrame = this._createSpriteFrameWithoutWarning();
// 给spriteFrame设置texture
spriteFrame.setTexture(texture);
// 获取节点上的cc.Sprite
var sprite = this.getComponent(cc.Sprite);
if (!sprite) {
sprite = this.addComponent(cc.Sprite);
}
// 替换节点cc.Sprite组件的cc.SpriteFrame
sprite.spriteFrame = spriteFrame;
this._setMySpriteFrame(spriteFrame);
},
loadRemoteImageWithUrlAndType: function(url, type = 'png') {
cc.loader.load({id: url, type: type}, (err, texture)=> {
if (!err) {
var size;
if (this.lockSize) {
size = this.node.getContentSize();
}
this._setTexture(texture);
if (this.lockSize) {
this.node.setContentSize(size);
}
}
});
},
onDestroy: function() {
cc.log('destroy');
this._releaseMySpriteFrame();
}
});
我对retain, release理解不深,希望Jare帅、Panda大神能指点一下。也希望官方能出更方便的远程图片加载方法!