Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add animated GIF support for Image on iOS #19411

Merged
merged 1 commit into from
Feb 16, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions THIRD-PARTY-NOTICES.TXT
Original file line number Diff line number Diff line change
Expand Up @@ -493,3 +493,31 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
=========================================


License notice for FFImageLoading
=========================================

(https://github.com/luberda-molinet/FFImageLoading/blob/master/LICENSE.md)

The MIT License (MIT)

Copyright (c) 2015 Daniel Luberda & Fabien Molinet

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
=========================================
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,15 @@
Minimum="0"
Maximum="60"
Value =" 10"/>
<Label
Text="Animated GIF"
Style="{StaticResource Headline}"/>
<ImageButton
x:Name="AnimatedGifImage"
Source="animated_heart.gif" />
<Button
Text="Use Online Source"
Clicked="UseOnlineSource_Clicked"/>
</VerticalStackLayout>
</ScrollView>
</views:BasePage.Content>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,12 @@ void OnResizeImageButtonClicked(object sender, EventArgs e)
ResizeImageButton.HeightRequest = 100;
ResizeImageButton.WidthRequest = 100;
}

void UseOnlineSource_Clicked(object sender, EventArgs e)
{
AnimatedGifImage.Source =
ImageSource.FromUri(new Uri("https://news.microsoft.com/wp-content/uploads/prod/2022/07/hexagon_print.gif"));
}
}

public class ImageButtonPageViewModel : BindableObject
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,19 @@
Background="Black"
Source="dotnet_bot.png"
/>
<Label
Text="Animated GIF"
Style="{StaticResource Headline}"/>
<Image
x:Name="AnimatedGifImage"
Source="animated_heart.gif"
IsAnimationPlaying="True" />
<Button
Text="Start/Stop"
Clicked="AnimationStartStop_Clicked"/>
<Button
Text="Use Online Source"
Clicked="UseOnlineSource_Clicked"/>
</VerticalStackLayout>
</ScrollView>
</views:BasePage.Content>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,5 +19,16 @@ protected override void OnAppearing()
var imageBytes = Convert.FromBase64String(Base64EncodedImage);
StreamSourceImage.Source = ImageSource.FromStream(() => new MemoryStream(imageBytes));
}

void AnimationStartStop_Clicked(object sender, EventArgs e)
{
AnimatedGifImage.IsAnimationPlaying = !AnimatedGifImage.IsAnimationPlaying;
}

void UseOnlineSource_Clicked(object sender, EventArgs e)
{
AnimatedGifImage.Source =
ImageSource.FromUri(new Uri("https://news.microsoft.com/wp-content/uploads/prod/2022/07/hexagon_print.gif"));
}
}
}
21 changes: 18 additions & 3 deletions src/Core/src/Handlers/Image/ImageHandler.iOS.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
#nullable enable
using System.Threading.Tasks;
using System.Threading.Tasks;
using UIKit;

namespace Microsoft.Maui.Handlers
Expand Down Expand Up @@ -51,7 +50,23 @@ public override void SetImageSource(UIImage? platformImage)
if (Handler?.PlatformView is not UIImageView imageView)
return;

imageView.Image = platformImage;
if (platformImage?.Images is not null)
{
imageView.Image = platformImage.Images[0];

imageView.AnimationImages = platformImage.Images;
imageView.AnimationDuration = platformImage.Duration;
}
else
{
imageView.AnimationImages = null;
imageView.AnimationDuration = 0.0;

imageView.Image = platformImage;
}

Handler?.UpdateValue(nameof(IImage.IsAnimationPlaying));

if (Handler?.VirtualView is IImage image && image.Source is IStreamImageSource)
imageView.InvalidateMeasure(image);
}
Expand Down
3 changes: 3 additions & 0 deletions src/Core/src/Handlers/ImageButton/ImageButtonHandler.iOS.cs
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,9 @@ public override void SetImageSource(UIImage? platformImage)
if (Handler?.PlatformView is not UIButton button)
return;

if (platformImage?.Images is not null && platformImage.Images.Length > 0)
platformImage = platformImage.Images[0];
PureWeen marked this conversation as resolved.
Show resolved Hide resolved

platformImage = platformImage?.ImageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal);

button.SetImage(platformImage, UIControlState.Normal);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,12 @@ public partial class FileImageSourceService

try
{
var image = imageSource.GetPlatformImage();

if (image == null)
using var cgImageSource = imageSource.GetPlatformImageSource(out var loadedScale);
PureWeen marked this conversation as resolved.
Show resolved Hide resolved
if (cgImageSource is null)
throw new InvalidOperationException("Unable to load image file.");

var image = cgImageSource.GetPlatformImage(loadedScale);

var result = new ImageSourceServiceResult(image, () => image.Dispose());

return FromResult(result);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,20 +21,12 @@ public partial class StreamImageSourceService

try
{
var stream = await imageSource.GetStreamAsync(cancellationToken).ConfigureAwait(false);
using var cgImageSource =
await imageSource.GetPlatformImageSourceAsync(cancellationToken).ConfigureAwait(false);
if (cgImageSource is null)
throw new InvalidOperationException("Unable to load image file.");

if (stream == null)
throw new InvalidOperationException("Unable to load image stream.");

using var data = NSData.FromStream(stream);
if (data == null)
throw new InvalidOperationException("Unable to load image stream data.");

// We do not need to pass the scale in here as the image file is not scaled to the screen scale.
var image = UIImage.LoadFromData(data);

if (image == null)
throw new InvalidOperationException("Unable to decode image from stream.");
var image = cgImageSource.GetPlatformImage();

var result = new ImageSourceServiceResult(image, () => image.Dispose());

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ namespace Microsoft.Maui
{
public partial class UriImageSourceService
{
internal string CacheDirectory = Path.Combine(FileSystem.CacheDirectory, "com.microsoft.maui", "MauiUriImages");
internal static readonly string CacheDirectory = Path.Combine(FileSystem.CacheDirectory, "com.microsoft.maui", "MauiUriImages");

public override Task<IImageSourceServiceResult<UIImage>?> GetImageAsync(IImageSource imageSource, float scale = 1, CancellationToken cancellationToken = default) =>
GetImageAsync((IUriImageSource)imageSource, scale, cancellationToken);
Expand All @@ -24,40 +24,13 @@ public partial class UriImageSourceService

try
{
var hash = Crc64.ComputeHashString(imageSource.Uri.OriginalString);
var pathToImageCache = CacheDirectory + hash + ".png";
var imageData = await DownloadAndCacheImageAsync(imageSource, cancellationToken);

NSData? imageData;

if (imageSource.CachingEnabled && IsImageCached(pathToImageCache))
{
imageData = GetCachedImage(pathToImageCache);
}
else
{
// TODO: use a real caching library with the URI
if (imageSource is not IStreamImageSource streamImageSource)
return null;

using var stream = await streamImageSource.GetStreamAsync(cancellationToken).ConfigureAwait(false);

if (stream == null)
throw new InvalidOperationException($"Unable to load image stream from URI '{imageSource.Uri}'.");

imageData = NSData.FromStream(stream);

if (imageData == null)
throw new InvalidOperationException("Unable to load image stream data.");

if (imageSource.CachingEnabled)
CacheImage(imageData, pathToImageCache);
}

// We do not need to pass the scale in here as the image file is not scaled to the screen scale.
var image = UIImage.LoadFromData(imageData);

if (image == null)
throw new InvalidOperationException($"Unable to decode image from URI '{imageSource.Uri}'.");
using var cgImageSource = imageData.GetPlatformImageSource();
if (cgImageSource is null)
throw new InvalidOperationException("Unable to load image file.");

var image = cgImageSource.GetPlatformImage();

var result = new ImageSourceServiceResult(image, () => image.Dispose());

Expand All @@ -70,6 +43,48 @@ public partial class UriImageSourceService
}
}

internal async Task<NSData> DownloadAndCacheImageAsync(IUriImageSource imageSource, CancellationToken cancellationToken)
{
// TODO: use a real caching library with the URI

var hash = Crc64.ComputeHashString(imageSource.Uri.OriginalString);
var ext = Path.GetExtension(imageSource.Uri.OriginalString);
var filename = $"{hash}{ext}";
var pathToImageCache = Path.Combine(CacheDirectory, filename);

NSData? imageData;

if (imageSource.CachingEnabled && IsImageCached(pathToImageCache))
{
imageData = GetCachedImage(pathToImageCache);
}
else
{
imageData = await DownloadImageAsync(imageSource, cancellationToken);
if (imageSource.CachingEnabled)
CacheImage(imageData, pathToImageCache);
}

return imageData;
}

internal static async Task<NSData> DownloadImageAsync(IUriImageSource imageSource, CancellationToken cancellationToken)
{
if (imageSource is not IStreamImageSource streamImageSource)
throw new InvalidOperationException($"Unable to load image stream from image source type '{imageSource.GetType()}'.");

using var stream = await streamImageSource.GetStreamAsync(cancellationToken).ConfigureAwait(false);
if (stream is null)
throw new InvalidOperationException($"Unable to load image stream from URI '{imageSource.Uri}'.");

var imageData = NSData.FromStream(stream);

if (imageData is null)
throw new InvalidOperationException("Unable to load image stream data.");

return imageData;
}

#pragma warning disable CA1822 // Mark members as static; Disabling because these methods are public and changing them to static is potentially a breaking change
public void CacheImage(NSData imageData, string path)
{
Expand Down Expand Up @@ -104,4 +119,4 @@ public NSData GetCachedImage(string path)
}
#pragma warning restore CA1822 // Mark members as static
}
}
}
Loading
Loading