Created
October 27, 2014 14:59
-
-
Save tombowers/511722e4aeb70fe3a1fa to your computer and use it in GitHub Desktop.
Xamarin Android – Image Caching
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
if (_memoryCache.Get(key) == null) | |
_memoryCache.Put(key, bitmap); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Get max available VM memory, exceeding this amount will throw an OutOfMemory exception. | |
// Stored in kilobytes as LruCache takes an int in its constructor. | |
var maxMemory = (int)(Java.Lang.Runtime.GetRuntime().MaxMemory() / 1024); | |
// Use 1/8th of the available memory for this memory cache. | |
int cacheSize = maxMemory / 8; | |
_memoryCache = new MemoryLimitedLruCache(cacheSize); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <summary> | |
/// LruCache limited by memory footprint in KB rather than number of items. | |
/// </summary> | |
public class MemoryLimitedLruCache : LruCache | |
{ | |
public MemoryLimitedLruCache(int size) : base(size) {} | |
protected override int SizeOf(Java.Lang.Object key, Java.Lang.Object value) | |
{ | |
// android.graphics.Bitmap.getByteCount() method isn't currently implemented in Xamarin. Invoke Java method. | |
IntPtr classRef = JNIEnv.FindClass("android/graphics/Bitmap"); | |
var getBytesMethodHandle = JNIEnv.GetMethodID(classRef, "getByteCount", "()I"); | |
var byteCount = JNIEnv.CallIntMethod(value.Handle, getBytesMethodHandle); | |
return byteCount / 1024; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment