Skip to content

Instantly share code, notes, and snippets.

@tombowers
Created October 27, 2014 14:59
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tombowers/511722e4aeb70fe3a1fa to your computer and use it in GitHub Desktop.
Save tombowers/511722e4aeb70fe3a1fa to your computer and use it in GitHub Desktop.
Xamarin Android – Image Caching
if (_memoryCache.Get(key) == null)
_memoryCache.Put(key, bitmap);
// 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);
/// <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