Last active
July 23, 2019 13:46
-
-
Save stewartsims/656802685e479d50a13e08c3ebefa126 to your computer and use it in GitHub Desktop.
Cross platform animated GIF in Xamarin Forms
This file contains hidden or 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
// 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; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Note that file access will vary depending on platform (best to use a file helper interface with platform specific implementations for this).