之前写到的tabgroup的自定义实现,确实存在很多的不灵活、代码也比较不规范;但不管怎么样,起码做到够用,我只会越做越好,你也一样。
这次也是关于Ti图片的处理,在做项目的时候,ti自身的imageview本来是够用的(有缓存、加载次数等等...具体的实现方法确实不知),但是有时候加载远程图片时却经常失败(图片大、android....),所以这次要讨论的就次是在ti的imageview上在做小小的改动。
enjoy ;)
exports.UI = {
/* modified version of https://gist.github.com/1243697
* adds detection of file extension rather than hard-coding .jpg as in the original
*/
_getExtension : function(fn) {
// from http://stackoverflow.com/a/680982/292947
var re = /(?:\.([^.]+))?$/;
var tmpext = re.exec(fn)[0];
return (tmpext) ? tmpext : '';
},
RemoteImage : function(a) {
a = a || {};
if (!a.image || a.image.indexOf('http') < 0) {
a.image = '/images/default.jpg';
} else {
a.decodeRetries = 10;
};
var md5;
var needsToSave = false;
var savedFile;
var noImage = Ti.App.Properties.getString('noImage');
var image_url = '';
if (a.image && a.image.indexOf('http') != -1) {
image_url = a.image;
md5 = Ti.Utils.md5HexDigest(a.image) + this._getExtension(a.image);
var appDataDir, cacheDir, externalRoot;
if(platform.isIOS){
savedFile = Titanium.Filesystem.getFile(
Titanium.Filesystem.applicationCacheDirectory,md5);
}else if(platform.isAndroid){
if (Ti.Filesystem.isExternalStoragePresent()) {
appDataDir = Ti.Filesystem.getFile('appdata://').nativePath;
externalRoot = appDataDir.substring(0, appDataDir.lastIndexOf('/'));
cacheDir = "" + externalRoot + "/Android/data/" + Ti.App.id + "/cache/_tmp/remote-cache";
savedFile = Titanium.Filesystem.getFile(cacheDir, md5);
} else {
savedFile = Titanium.Filesystem.getFile(Titanium.Filesystem.applicationCacheDirectory, md5);
}
}
if(savedFile.exists()){
a.image = savedFile;
} else {
needsToSave = true;
}
}
if (noImage == 'YES') {
a.image = '/images/default.jpg';
needsToSave = false;
}
if (needsToSave === true && (image_url.indexOf('http') != -1)) {
var xhr = Ti.Network.createHTTPClient();
xhr.onload = function() {
if (xhr.status == 200) {
try {
savedFile.write(xhr.responseData);
a.image = savedFile.nativePath;
} catch(e) {
Ti.API.error('error when reading from file stream');
}
};
};
if (image_url && image_url.indexOf('undefined') == -1) {
xhr.open('GET', image_url);
xhr.send();
}
}
var image = Ti.UI.createImageView(a);
if (typeof a.image == 'string' && a.image.indexOf('http') != -1) {
getImageView(image, a.image);
}
return image;
}
};
function getImageView(imageView, URL) {
imageView.image = '/images/default.jpg';
try {
var c = Titanium.Network.createHTTPClient();
c.setTimeout(10000);
c.onerror = function() {
};
c.onload = function() {
if (c.status == 200) {
imageView.image = this.responseData;
}
}
if (URL && URL.indexOf('undefined') == -1 && URL.indexOf('http') > -1) {
c.open('GET', URL);
c.send();
}
} catch(e) {
}
}