根据默认图片的大小和位置,显示远程图片,只需要把组件挂载在Sprite上,需要更新的时候,调用以下方法即可。
只有url调用如下:
userHead.getComponent('ImageUrl').loadUrl(url);
知道图片类型调用如下(如微信头像):
userHead.getComponent('ImageUrl').loadUrl(url,'png');
实现核心代码如下:
/**
* @description: 获取Url图
* @param {string} url 路径
* @param {string} type 图片类型,如:png
* @return:
*/
loadUrl(url, type = null){
this.checkDefault();
if(url == null || url == ''){
cc.error('invalid url', url);
this.getComponent(cc.Sprite).spriteFrame = this._defaultSpf;
return;
}
cc.loader.load(typeof type == 'string'? {url: url, type: type}: url, (err, texture) => {
if(err != null){
cc.error(url, err);
return;
}
// 根据默认大小显示
this.getComponent(cc.Sprite).spriteFrame = new cc.SpriteFrame(texture);
let size = this._defaultSpf.getOriginalSize();
this.node.width = size.width;
this.node.height = size.height;
});
},
实现源码:https://github.com/caizj-cn/pgy_js_lib/blob/master/util/ImageUrl.js