如何在creator中加载远程图片

请问大神,我想在creator中实现自定义头像功能,遇到一个问题:
我从远程下载图片到本地后,也动态加载到内存了,如何在creator里显示出来呢?

同求6个字!

顶顶顶顶 同求

cc.loader.load("url", function(err, texture){
      var sprite = node.getComponent(cc.Sprite);
      sprite.spriteFrame = new cc.SpriteFrame(texture);
})

大概是这样,手打代码,可能有写错的地方

1赞

这样的做法,每次打开都要下载一遍,请问,能否将图片保存到本地,然后进行加载呢?

loadImage:function(url, callback)
{
if(url==null || typeof(url) == ‘undefined’) return;
if (!cc.sys.isNative) return;
var dirpath = jsb.fileUtils.getWritablePath() + ‘custom_head_img/’;
var filepath = dirpath + url + ‘.jpg’;
function loadEnd()
{

        cc.loader.load(filepath, function(err, tex)
        {
            
            if( err )
            {
                // cc.error(err);
            }
            else
            {
                var spriteFrame = new cc.SpriteFrame(tex);
                spriteFrame.retain();
                callback(spriteFrame);
            }
        });
    }

    if( jsb.fileUtils.isFileExist(filepath) ){
        cc.log('Remote is find' + filepath);
        loadEnd();
        return;
    }

    var saveFile = function(data)
    {
        if( typeof data !== 'undefined' )
        {
            if( !jsb.fileUtils.isDirectoryExist(dirpath) )
            {
                jsb.fileUtils.createDirectory(dirpath);
            }

            if( jsb.fileUtils.writeDataToFile(  new Uint8Array(data) , filepath) )
            {
                cc.log('Remote write file succeed.');
                loadEnd();
            }
            else
            {
                cc.log('Remote write file failed.');
            }
        }
        else
        {
            cc.log('Remote download file failed.');
        }
    };
    

    var t = url.substr(0,2);
    var loadpath = constDef.CUSTOM_HEAD_URL+t+"/"+url+".jpg";

    var xhr = new XMLHttpRequest();
    xhr.timeout = 10000; //毫秒单位
    xhr.ontimeout = function()
    {
        xhr.abort(); //重置 
        //重新请求
        xhr.open("GET", loadpath, true);
        xhr.send();
    }.bind(this);
   
    xhr.onreadystatechange = function () 
    {
        if (xhr.readyState === 4 ) {
            if(xhr.status === 200||xhr.status === 304){
                xhr.responseType = 'arraybuffer';
                saveFile(xhr.response);
            }else{
                saveFile(null);
            }
        }
    }.bind(this);
    xhr.open("GET", loadpath, true);
    xhr.send();
},

这个应该可以满足你的要求

3赞

jsb.fileUtils 这个应该怎么用?浏览器,打包都不行。还需要引用什么吗?

如果远程图片有修改,本地有缓存,你这个就不管用了,不能显示最新的图片。

请问这个“loadpath”定义中的
var loadpath = constDef.CUSTOM_HEAD_URL+t+"/"+url+".jpg";怎么理解的呀?
然后“spriteFrame.retain();”,retain之后,我在调用以后,什么时候去释放这个sprite呢?
谢谢

您好,我的主要疑问在“constDef.CUSTOM_HEAD_URL+t+”这里。不知道这两个变量具体指代什么?

解决方案看这篇博客:
https://www.jianshu.com/p/a5c77a045063