Skip to content

Instantly share code, notes, and snippets.

@Clancey
Created April 6, 2016 19:45
Show Gist options
  • Save Clancey/998ffa36f1aab5448cb08353f39c7c12 to your computer and use it in GitHub Desktop.
Save Clancey/998ffa36f1aab5448cb08353f39c7c12 to your computer and use it in GitHub Desktop.
Android SVG Image Cache
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using Android.Graphics.Drawables;
using System.Threading.Tasks;
using Xamarin.Forms.Platform.Android;
public static class ImageCacheService
{
static readonly string CacheLocation = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal),"ImageCache");
static readonly NGraphics.IPlatform Platform = new NGraphics.AndroidPlatform();
static ImageCacheService()
{
Directory.CreateDirectory(CacheLocation);
}
public static async Task<Drawable> GetImage(VectorImage vector, int width, int height, Xamarin.Forms.Color? color)
{
try{
var resourceName = ImagePaths.ResourceIdForVector(vector);
var fileName = Path.GetFileNameWithoutExtension(resourceName);
fileName = $"{fileName} {width} {height}.png";
var filePath = Path.Combine(CacheLocation, fileName);
if (File.Exists(filePath)) {
return ApplyTint(await Drawable.CreateFromPathAsync(filePath),color);
}
using (var file = new System.IO.StreamReader(ResourceLoader.GetEmbeddedResourceStream(resourceName)))
{
var size = new NGraphics.Size(width, height);
var graphic = NGraphics.Graphic.LoadSvg(file);
//Shame on Size not being Equatable ;)
if (size.Width <= 0 || size.Height <= 0)
size = graphic.Size;
var gSize = graphic.Size;
if (gSize.Width > size.Width || size.Height > gSize.Height)
{
var ratioX = size.Width / gSize.Width;
var ratioY = size.Height / gSize.Height;
var ratio = Math.Min(ratioY, ratioX);
graphic.Size = size = new NGraphics.Size(gSize.Width * ratio, gSize.Height * ratio);
}
double Scale = (int)Xamarin.Forms.Forms.Context.Resources.DisplayMetrics.DensityDpi / 160f;
var c = Platform.CreateImageCanvas(size, Scale);
graphic.Draw(c);
var image = c.GetImage() as NGraphics.BitmapImage;
if(image.Bitmap == null)
{
throw new Exception("Foo");
}
await image.Bitmap.CompressAsync(Android.Graphics.Bitmap.CompressFormat.Png, 100, File.Open(filePath, FileMode.Create));
return ApplyTint(new BitmapDrawable(image.Bitmap),color);
}
}
catch(Exception ex) {
Console.WriteLine("Error loading Vector {0}", vector);
Console.WriteLine(ex);
}
return null;
}
static Drawable ApplyTint(Drawable drawable, Xamarin.Forms.Color? color)
{
if (color == null || drawable == null)
return drawable;
var filter = new Android.Graphics.PorterDuffColorFilter(color.Value.ToAndroid(), Android.Graphics.PorterDuff.Mode.SrcAtop);
drawable.SetColorFilter(filter);
return drawable;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment