使用$ImageCacheFactory预加载所有图片

4

我使用ionic框架创建了一个移动应用程序,其中包含许多图像。我需要在不闪烁的情况下加载所有图像。因此,我使用了$ImageCacheFactory来预加载所有图像,参考了这篇博客

我使用了以下代码。问题是该应用程序包含100个png图像,因此我必须引用所有png文件。

.run(function($ImageCacheFactory) {
    $ImageCacheFactory.Cache([
        "img/user.png", 
        "img/profile.png",
        "img/logo.png",
        "img/splash.png", 
        "img/map.png", 
        "img/shop.png",
        "img/country.png", 
        "img/place.png"
      ]).then(function(){
         console.log("Images done loading!");
      },function(failed){
          console.log("Error..!!!");
    });
})

有没有一种简单的方法可以用一行代码引用所有PNG图像(所有图像都在www/img文件夹中)?谢谢
2个回答

3
创建一个Angular工厂,代码如下:
.factory("$fileFactory", function($q) {

  var File = function() {};

  File.prototype = {

    getEntries: function(path) {
      var deferred = $q.defer();
      window.resolveLocalFileSystemURI(path, function(fileSystem) {
        var directoryReader = fileSystem.createReader();
        directoryReader.readEntries(function(entries) {
          deferred.resolve(entries);
        }, function(error) {
          deferred.reject(error);
        });
      }, function(error) {
        deferred.reject(error);
      });
      return deferred.promise;
    }

  };

  return File;

});

然后使用 getEntries() 获取所有文件的列表

.run(function($ImageCacheFactory, $ionicPlatform, $fileFactory ) {
  var fs = new $fileFactory();
  $ionicPlatform.ready(function() {
    fs.getEntries('img').then(function(result) {
      var files = result;
      files = files.unshift({
        name: "[parent]"
      }).map(function(i, v) {
        return 'img/' + v.name;
      });
      $ImageCacheFactory.Cache(files).then(function() {
        console.log("Images done loading!");
      }, function(failed) {
        console.log("Error..!!!");
      });
    })
  });
});

您需要安装依赖项 Apache Cordova 文件

cordova plugin add https://git-wip-us.apache.org/repos/asf/cordova-plugin-file.git

参考资料: 有用的教程


1
谢谢伙计,你帮我省了时间。 - Muhsin Keloth
这也会获取img目录下的子文件夹吗? - lunacafu

0

很抱歉我还没有答案。但我知道为什么它不起作用。

使用Web浏览器

不要这样做。如果你试图在Web浏览器中打开这个项目,你就会自讨苦吃。这个应用程序使用本地设备插件,而Web浏览器不熟悉这些插件。因此,这将导致奇怪的错误。


如果这不是一个答案,将翻译的文本作为问题的评论可能更好。 - hubson bropa

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接