在做排行榜时使用微信的接口wx.getFriendCloudStorage()获得了很多信息,除了显示分数外,还需要显示用户头像,刚开始想到的是使用cc.loader.load,但是按照网上很多的帖子上的方法都无法成功加载,真机调试时一直提示“未成功加载到该图片或资源”,后来在一个论坛里终于找到了方法。可以成功显示头像了。
代码如下:
createImage(sprite,url){//这个方法时引擎团队的某大大提供的,我找不到网址了,暂时用一下,希望大大不要介意
let image = wx.createImage();
image.onload = function () {
let texture = new cc.Texture2D();
texture.initWithElement(image);
texture.handleLoadedTexture();
sprite.spriteFrame = new cc.SpriteFrame(texture);
sprite.node.width=50;
sprite.node.height=50;
};
image.src = url;
},
参数sprite是节点的sprite,url则是从wx.getFriendCloudStorage()接口获得的数据avatarUrl(用户头像url,将该url直接复制到浏览器搜索栏,可以看到一张小图).
附上个人的部分代码,便于大家查看:
showList(){
var self=this;
this.view.active=true;
var kvDataList = new Array();
kvDataList.push({
key: “score”,
value:String(this._Score)//该处必须将整型转换为字符型,否则无法上传成功
});
console.log(“kvDataList[0].value:”+kvDataList[0].value);
wx.setUserCloudStorage({
KVDataList: kvDataList,
success:function(res){
console.log(“上传成功:”);
console.log(res);
},
fail:function(res){
console.log(“上传失败:”);
console.log(res);
}
});
wx.getFriendCloudStorage({
keyList: ['score'],
success: function (res) {
console.log(res);
if(res.data.length<=6){
self.ColorBg.active=false;
}
for(var i in res.data){
console.log("value:"+res.data[i].KVDataList[i].value);
self.Label.children[i].getChildByName("name").getComponent(cc.Label).string=res.data[i].nickname;
self.Label.children[i].getChildByName("score").getComponent(cc.Label).string=res.data[i].KVDataList[i].value;
self.createImage(self.Label.children[i].getChildByName("headimage").getComponent(cc.Sprite),res.data[i].avatarUrl);
}
},
fail:function(res){
console.log(res);
}
});
},
createImage(sprite,url){
let image = wx.createImage();
image.onload = function () {
let texture = new cc.Texture2D();
texture.initWithElement(image);
texture.handleLoadedTexture();
sprite.spriteFrame = new cc.SpriteFrame(texture);
sprite.node.width=50;
sprite.node.height=50;
};
image.src = url;
},