Skip to content

Instantly share code, notes, and snippets.

@Adam--
Last active June 8, 2018 14:53
Show Gist options
  • Save Adam--/72af888c2851e409be87ba32117dfb3f to your computer and use it in GitHub Desktop.
Save Adam--/72af888c2851e409be87ba32117dfb3f to your computer and use it in GitHub Desktop.
Android GifImageView custom renderer for Xamarin Forms
namespace LakeShore.Sources.Core.Instrument
{
using Xamarin.Forms;
public class GifImageView : View
{
public static readonly BindableProperty SourceProperty = BindableProperty.Create(
propertyName: nameof(Source),
returnType: typeof(string),
declaringType: typeof(GifImageView),
defaultValue: string.Empty);
public string Source
{
get { return (string)this.GetValue(SourceProperty); }
set { this.SetValue(SourceProperty, value); }
}
}
}
using LakeShore.Sources.Core.Instrument;
using LakeShore.Sources.Droid.Instrument.CustomRenderers;
using Xamarin.Forms;
[assembly: ExportRenderer(typeof(GifImageView), typeof(GifImageViewCustomRenderer))]
namespace LakeShore.Sources.Droid.Instrument.CustomRenderers
{
using System.ComponentModel;
using System.IO;
using LakeShore.Sources.Core.Instrument;
using Xamarin.Forms.Platform.Android;
using AGifImageView = Felipecsl.GifImageViewLibrary.GifImageView;
public class GifImageViewCustomRenderer : ViewRenderer<GifImageView, AGifImageView>
{
public GifImageViewCustomRenderer()
{
this.AutoPackage = false;
}
protected override void OnElementChanged(ElementChangedEventArgs<GifImageView> e)
{
base.OnElementChanged(e);
if (this.Control == null)
{
this.SetNativeControl(new AGifImageView(this.Context));
this.SetSourceAndAnimate();
}
}
protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
{
base.OnElementPropertyChanged(sender, e);
if (e.PropertyName == nameof(GifImageView.Source) && this.Control != null)
{
this.SetSourceAndAnimate();
}
}
private void SetSourceAndAnimate()
{
try
{
byte[] bytes;
using (var stream = new MemoryStream())
{
this.Context.Assets.Open(this.Element.Source).CopyTo(stream);
bytes = stream.ToArray();
}
this.Control.SetBytes(bytes);
this.Control.StartAnimation();
}
catch (Java.IO.IOException ex)
{
Android.Util.Log.Error(nameof(GifImageViewCustomRenderer), ex, $"Failed to open source {this.Element.Source}");
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment