Skip to content

Instantly share code, notes, and snippets.

@stewartsims
Last active July 23, 2019 13:46
Show Gist options
  • Save stewartsims/656802685e479d50a13e08c3ebefa126 to your computer and use it in GitHub Desktop.
Save stewartsims/656802685e479d50a13e08c3ebefa126 to your computer and use it in GitHub Desktop.
Cross platform animated GIF in Xamarin Forms
// in your XAML
<WebView x:Name="AnimatedGIF" HorizontalOptions="Center" VerticalOptions="Center" WidthRequest="64" HeightRequest="64" BackgroundColor="#336699"></WebView>
// in your CS (constructor)
AnimatedGIF.Source = GifViewHelper.GetGifViewSource("my-animation.gif", AnimatedGIF.BackgroundColor);
// the helper class
public class GifViewHelper
{
public static HtmlWebViewSource GetGifViewSource(string filename, Color backgroundColour)
{
string background = GetHexString(backgroundColour);
HtmlWebViewSource source = new HtmlWebViewSource();
source.Html = string.Empty;
string base64 = Convert.ToBase64String(File.ReadAllBytes(filename));
string mimeType = "image/gif";
source.Html = "<html><body style=\"margin:0px; padding:0px; background:" + background + ";\"><img src=\"data:" + mimeType + ";base64," + base64 + "\" width=\"100%\" height=\"100%\"></body></html>";
return source;
}
public static string GetHexString(Color color)
{
var red = (int)(color.R * 255);
var green = (int)(color.G * 255);
var blue = (int)(color.B * 255);
var hex = $"#{red:X2}{green:X2}{blue:X2}";
return hex;
}
}
@stewartsims
Copy link
Author

@stewartsims
Copy link
Author

Note that file access will vary depending on platform (best to use a file helper interface with platform specific implementations for this).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment