RessourceManager aka ImageCache
Monkey Forums/Monkey Code/RessourceManager aka ImageCache
| ||
This can be used so images are not loaded twice. It also acts as a manual cache, example below. Module [monkeycode] Strict Import mojo.graphics '-------------------------------------------------------------------------- ' ** Cache for Images '-------------------------------------------------------------------------- Class ImageCache '-------------------------------------------------------------------------- ' * Get an Image from the Cache + Load in Temporary if not there '-------------------------------------------------------------------------- Function Get:Image( path:String ) If Temporary.Contains( path ) Return Temporary.Get( path ) ElseIf Permanent.Contains( path ) Return Permanent.Get( path ) Else Local image:Image = LoadImage( path, 1, Image.DefaultFlags ) If Not image Then Return Null Temporary.Set( path, image ) Return image End End '-------------------------------------------------------------------------- ' * Upload an Image into the Permanent Cache '-------------------------------------------------------------------------- Function Upload:Image( path:String ) Local image:Image = LoadImage( path, 1, Image.DefaultFlags ) If Not image Then Return Null Permanent.Set( path, image ) Return image End '-------------------------------------------------------------------------- ' * Clear the Temporary Cache ' Optionally also the Permanent Cache '-------------------------------------------------------------------------- Function Clear:Void() For Local img:Image = Eachin Temporary.Values() img.Discard() Next Temporary.Clear() End '-------------------------------------------------------------------------- Private '-------------------------------------------------------------------------- Global Temporary:StringMap<Image> = New StringMap<Image> Global Permanent:StringMap<Image> = New StringMap<Image> End [/monkeycode] How to use [monkeycode] 'This will load the image if not already loaded, else it gives you a reference from the already loaded one Local image:Image = ImageCache.Get("image1.png") 'You could also do this for just loading the image without assigning and it will be placed in the cache ImageCache.Get("image1.png") [/monkeycode] The 2 above will get loaded into the temporary-cache. In my game I clear this at the end of each level via the Clear() Method. If you want to keep certain ressources longer in your game (like the player) do the following: [monkeycode] ImageCache.Upload("image1.png") [/monkeycode] This ensures the image will permanently stay in memory, even after you call Clear(). Hope you like it. |
| ||
I like it, thanks for that! :) |