Advertisement
Guest User

Untitled

a guest
Nov 29th, 2015
248
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Haxe 1.50 KB | None | 0 0
  1. class CachedImage extends Sprite
  2. {
  3.     private var dir:String;
  4.     private var loader:Loader;
  5.     public function new(w:Float = 0, h:Float = 0, path:String)
  6.     {
  7.         super();
  8.         this.graphics.beginFill(0xFFFFFF, 0.1);
  9.         this.graphics.drawRect(0, 0, w, h);
  10.        
  11.         dir = SystemPath.applicationStorageDirectory + "\\" + resolvePath(path);
  12.         var splitDir:Array<String> = dir.split("\\");
  13.        
  14.         createFolder(splitDir.splice(0, splitDir.length - 1).join("\\"));
  15.         loader = new Loader();
  16.         addChild(loader);
  17.         loader.alpha = 0;
  18.         loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onLoaderComplete);
  19.         var request:URLRequest = new URLRequest();
  20.         if (FileSystem.exists(dir))
  21.         {
  22.             trace("load from cache");
  23.             request.url = dir;
  24.         }
  25.         else
  26.         {
  27.             trace("load from url");
  28.             request.url = path;
  29.         }
  30.         loader.load(request);
  31.     }
  32.    
  33.     private function createFolder(s:String):Void
  34.     {
  35.         if (!FileSystem.exists(s))
  36.         {
  37.             try
  38.             {
  39.                 FileSystem.createDirectory(s);
  40.             }
  41.         }
  42.     }
  43.    
  44.     private function onLoaderComplete(e:Event):Void
  45.     {
  46.         loader.contentLoaderInfo.removeEventListener(Event.COMPLETE, onLoaderComplete);
  47.         Actuate.tween(loader, 0.5, { alpha:1 } );
  48.         if(!FileSystem.exists(dir))
  49.         {
  50.             try
  51.             {
  52.                 File.saveBytes(dir, loader.contentLoaderInfo.bytes);
  53.             }
  54.         }
  55.     }
  56.     public static function resolvePath(path:String):String
  57.     {
  58.         path = StringTools.replace(path, "http://", "");
  59.         path = StringTools.replace(path, "https://", "");
  60.         path = StringTools.replace(path, "/", "\\");
  61.         return path;
  62.     }
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement