cocos 在原生中的 Imageloader
2018-04-17 本文已影响0人
wlssing
var urlPool = new Map();//预防文件多次下载
var cacheFileName = "cocosImageCache/";
function initLoader() {
if (cc.sys.isNative) {
var dirpath = jsb.fileUtils.getWritablePath() + cacheFileName;
if (!jsb.fileUtils.isDirectoryExist(dirpath)) {
//logUtil.logDebug("loadImage 1 loadNetImage !isDirectoryExist");
if (jsb.fileUtils.createDirectory(dirpath)) {
//logUtil.logDebug("loadImage 1 loadNetImage createDirectories success");
} else {
//logUtil.logDebug("loadImage 1 loadNetImage createDirectories failed");
}
} else {
//logUtil.logDebug("loadImage 1 loadNetImage isDirectoryExist");
}
}
}
function load(sprite, defaultUrl, url) {
if (!sprite) {
//logUtil.logDebug("loadImage 1 load sprite == null");
return;
}
//给该精灵加上url标签 防止复用时 异步多次回调 且回调顺序不一致的情况
if (defaultUrl) {
sprite.defaultUrlTag = defaultUrl;
}
if (!url) {
if (defaultUrl) {
//logUtil.logDebug("loadImage 1 load url == null");
loadDefault(defaultUrl, sprite);
return;
} else {
//logUtil.logDebug("loadImage 1 load url&&defaultUrl == null");
return;
}
} else {
sprite.urlTag = url;
var img = cc.loader.getRes(defaultUrl);
if (sprite.defaultUrlTag === defaultUrl) {
if (!img) {
//logUtil.logDebug("loadImage 1 load first load default sprite.defaultUrlTag != defaultUrl");
loadDefault(defaultUrl, sprite);
} else {
sprite.spriteFrame = new cc.SpriteFrame(img);
}
}
}
if (url.startsWith("http")) {
//logUtil.logDebug("loadImage 2 load http" + url);
loadFromNet(url, sprite, defaultUrl);
} else {
//logUtil.logDebug("loadImage 2 load res" + url);
loadWithOutFileCache(url, sprite);
}
};
//是否第一次下载
function isFirstDownloading(url, sprite) {
var sprites = urlPool.get(url);
if (sprites) {
sprites.push(sprite);
//logUtil.logDebug("loadImage 1 isFirstDownloading sprite != null");
return false;
} else {
var spArr = new Array();
spArr.push(sprite);
//logUtil.logDebug("loadImage 1 isFirstDownloading sprite == null");
urlPool.set(url, spArr);
return true;
}
};
function getCacheArray(url) {
var sprites = urlPool.get(url);
return sprites;
};
function isFitTag(sprite, url) {
if (!sprite) {
return false;
}
return sprite.urlTag === url;
};
//比较缓存文件路径是否相同
function isFitFileTag(sprite, path) {
if (!sprite) {
return false;
}
var dirpath = jsb.fileUtils.getWritablePath() + cacheFileName;
var filepath = dirpath + farmGame.util.Base64Encode(sprite.urlTag);
return filepath === path;
};
//获取图片的格式 这里有个bug 微信头像没后缀 必须带上个后缀(不论后缀对不对)才能显示 cocos的bug
function getImageType(url) {
if (isContains(url, 'jpg')) {
return 'jpg';
} else if (isContains(url, "webp")) {
return 'webp';
} else {
return 'png';
}
};
function isContains(str, substr) {
return new RegExp(substr).test(str);
};
//不能单独使用
function loadFromNet(url, sprite) {
if (cc.sys.isNative) {
//logUtil.logDebug("loadImage 1 loadNetImage isNative" + url);
// 如果是手机的jsb,走文件缓存
var dirpath = jsb.fileUtils.getWritablePath() + cacheFileName;
var filepath = dirpath + farmGame.util.Base64Encode(url);
if (jsb.fileUtils.isFileExist(filepath)) {
//文件存在
//logUtil.logDebug("loadImage 2 loadNetImage load to memory cache" + url);
loadWithTag(filepath, sprite);
return;
}
//文件不存在 判断是否请求过 并将精灵加入回调队列
if (isFirstDownloading(url, sprite)) {
try {
dowloadImage(url, sprite);
} catch (error) {
//logUtil.logDebug("loadImage 1 loadNetImage isFirstDownloading error" + error);
}
} else {
//logUtil.logDebug("loadImage 10 loadNetImage already request " + url);
}
} else {
//logUtil.logDebug("loadImage 11 loadNetImage !isNative" + url);
// 如果不是手机的jsb,直接加载
loadWithOutFileCache(url, sprite);
}
};
function isImageUrl(url) {
if (url) {
if (url.endsWith(".png") || url.endsWith(".jpg")) {
return true;
}
}
return false;
};
//不能单独使用
function loadWithTag(url, sprite) {//url全部为本地路劲
//logUtil.logDebug("loadImage 1 loadWithTag load local resource" + url);
if (url && isFitFileTag(sprite, url)) {
//logUtil.logDebug("loadImage 2 loadWithTag load url fit" + url);
var img = cc.loader.getRes(url);
if (img) {//直接从内存缓存中取
//logUtil.logDebug("loadImage 3 loadWithTag get cache from memory" + url);
sprite.spriteFrame = new cc.SpriteFrame(img);
return;
}
//logUtil.logDebug("loadImage 4 loadWithTag load url fit not in memory cache" + url);
cc.loader.load({url: url, type: getImageType(sprite.urlTag)}, function (err, texture) {
if (err) {
//logUtil.logDebug("loadImage 5 loadWithTag load local resource failed" + url);
// loadDefault(defaultUrl, sprite);
return;
}
if (isFitFileTag(sprite, url)) {//异步回调时 查看当前view是否变化了请求链接 在复用的时候会有问题
//logUtil.logDebug("loadImage 6 loadWithTag isloaded ");
sprite.spriteFrame = new cc.SpriteFrame(texture);
} else {
//logUtil.logDebug("loadImage 7 loadWithTag url is diffrent with sprite.urlTag");
}
});
}
};
//直接请求不缓存//不能单独使用
function loadWithOutFileCache(url, sprite) {
//logUtil.logDebug("loadImage 1 directLoadImage load local resource" + url);
if (url) {
var imgCache = cc.loader.getRes(url);//直接从内存缓存中取
if (imgCache) {
//logUtil.logDebug("loadImage 2 directLoadImage get cache from memory" + url);
sprite.spriteFrame = new cc.SpriteFrame(imgCache);
return;
}
cc.loader.load({url: url, type: getImageType(sprite.urlTag)}, function (err, texture) {
if (err) {
//logUtil.logDebug("loadImage 3 directLoadImage load local resource failed" + url);
return;
}
if (url === sprite.urlTag) {
//logUtil.logDebug("loadImage 2 directLoadImage isloaded" + url);
sprite.spriteFrame = new cc.SpriteFrame(texture);
} else {
//logUtil.logDebug("loadImage 4 directLoadImage url is diffrent with sprite.urlTag");
}
});
}
};
//不能单独使用
function loadDefault(defaultUrl, sprite) {
//logUtil.logDebug("loadImage 1 loadDefault 1load default res" + defaultUrl);
if (defaultUrl) {
cc.loader.load({url: defaultUrl, type: 'png'}, function (err, texture) {
if (err) {
//logUtil.logDebug("loadImage 2 loadDefault load default res failed" + defaultUrl);
return;
}
//logUtil.logDebug("loadImage 2 loadDefault isloaded" + defaultUrl + "defaultUrlTag" + sprite.defaultUrlTag);
if (defaultUrl === sprite.defaultUrlTag ) {
sprite.spriteFrame = new cc.SpriteFrame(texture);
} else {
//logUtil.logDebug("loadImage 2 loadDefault sprite.defaultUrlTag is not fit" + sprite.defaultUrlTag + " " + sprite.urlTag);
}
});
}
};
function doError(url) {
try {
// //logUtil.logDebug("loadImage 3 loadNetImage doError!!!!:" + "errorstr:" + errorStr + ":errorCode:" + errorCode + ":errInter:" + errorCodeInternal.toString());
var cacheArr = getCacheArray(url);
for (var k in cacheArr) {//
var spritetmp = cacheArr[k];
//logUtil.logDebug("loadImage 4 loadNetImage doError load default" + k + "spritetmp" + spritetmp);
loadWithOutFileCache(spritetmp.urlTag, spritetmp);
}
//logUtil.logDebug("loadImage 5 loadNetImage doError delete " + url);
urlPool.delete(url);
} catch (error) {
//logUtil.logDebug("loadImage 1 loadNetImage doError error" + error);
} finally {
urlPool.delete(url);
}
};
function doSuccess(url) {
try {
//logUtil.logDebug("loadImage 6 loadNetImage doSuccess down success!!!!:");
var cacheArr = getCacheArray(url);
//logUtil.logDebug("loadImage 7 loadNetImage doSuccess down success!!!!cacheArr:" + cacheArr.length);
for (var k in cacheArr) {//
var spritetmp = cacheArr[k];
var dirpath = jsb.fileUtils.getWritablePath() + cacheFileName;
var filepath = dirpath + farmGame.util.Base64Encode(url);
//logUtil.logDebug("loadImage 8 loadNetImage doSuccess load file to memory cache " + k + "url:" + url);
loadWithTag(filepath, spritetmp);
}
//logUtil.logDebug("loadImage 9 loadNetImage doSuccess delete " + url);
} catch (error) {
//logUtil.logDebug("loadImage 1 loadNetImage doSuccess error" + error);
} finally {
urlPool.delete(url);
}
};
function httpRequest(address, callback) {
try {
var xhr = new XMLHttpRequest();
var self = this;
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
if (xhr.status >= 200 && xhr.status < 400) {
//logUtil.logDebug("loadImage 网络请求成功");
if (callback) {
//logUtil.logDebug("loadImage 回调开始");
callback(xhr)
} else {
//logUtil.logDebug("loadImage 回调失败 callback == null");
}
} else {
//logUtil.logDebug("loadImage 网络请求失败" + xhr.status+" address:"+address);
doError(address);
}
} else {
//logUtil.logDebug("loadImage 网络 请求状态变化" + xhr.status);
}
};
xhr.timeout = 10000;
xhr.onerror = function (err) {
//logUtil.logDebug("loadImage 网络访问发生错误,请检查网络是否畅通22.");
doError(address);
};
xhr.ontimeout = function () {
// self.close(xhr);
//logUtil.logDebug("loadImage 网络请求超时,请保证你的网络环境稳定.");
doError(address);
};
xhr.responseType = "arraybuffer";
xhr.open("GET", address, true);
xhr.send();
}catch (error) {
//logUtil.logDebug("loadImage 1 网络请求错误 catch error" + error);
} finally {
}
};
function saveTemp(file_name, data) {
return jsb.fileUtils.writeDataToFile(data, file_name)
};
function dowloadImage(url, sprite) {
//logUtil.logDebug("loadImage 网络请求开始");
httpRequest(url, function (xhr) {
try{
//logUtil.logDebug("loadImage 回调开始 start");
var tmp_data = new Uint8Array(xhr.response);
var dirpath = jsb.fileUtils.getWritablePath() + cacheFileName;
//logUtil.logDebug("loadImage 回调 dirpath"+dirpath);
var filepath = dirpath + farmGame.util.Base64Encode(url);
//logUtil.logDebug("loadImage 回调 filepath"+filepath);
var res = saveTemp(filepath, tmp_data)
//logUtil.logDebug("loadImage 回调 存储"+res);
if (res) {
//logUtil.logDebug("loadImage 文件存储成功" + url+" filepath:"+filepath);
doSuccess(url);
} else {
//logUtil.logDebug("loadImage 文件存储失败" + url+" filepath:"+filepath);
doError(url);
}
}catch (error) {
//logUtil.logDebug("loadImage 1 回调错误 catcherror" + error);
} finally {
}
})
};
module.exports = {
load: load,
initLoader: initLoader,
}