XAML-Map-Control/MapControl/WinUI/ImageTile.WinUI.cs

108 lines
3.2 KiB
C#
Raw Normal View History

using System;
using System.Threading.Tasks;
#if UWP
using Windows.UI.Core;
2021-07-02 21:18:39 +02:00
using Windows.UI.Xaml;
2025-11-13 15:32:01 +01:00
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Media.Animation;
2021-07-02 21:18:39 +02:00
using Windows.UI.Xaml.Media.Imaging;
2024-05-22 11:25:32 +02:00
#else
using Microsoft.UI.Dispatching;
2024-05-22 11:25:32 +02:00
using Microsoft.UI.Xaml;
2025-11-13 15:32:01 +01:00
using Microsoft.UI.Xaml.Controls;
using Microsoft.UI.Xaml.Media;
2024-05-22 11:25:32 +02:00
using Microsoft.UI.Xaml.Media.Animation;
using Microsoft.UI.Xaml.Media.Imaging;
2021-06-14 21:41:37 +02:00
#endif
namespace MapControl
{
2025-11-13 15:32:01 +01:00
public class ImageTile(int zoomLevel, int x, int y, int columnCount)
: Tile(zoomLevel, x, y, columnCount)
{
2025-11-20 09:16:52 +01:00
public Image Image { get; } = new Image { Stretch = Stretch.Fill };
2025-11-13 15:32:01 +01:00
public override async Task LoadImageAsync(Func<Task<ImageSource>> loadImageFunc)
{
var tcs = new TaskCompletionSource<object>();
async void LoadAndSetImageSource()
{
try
{
var image = await loadImageFunc();
Image.Source = image;
if (image != null && MapBase.ImageFadeDuration > TimeSpan.Zero)
{
if (image is BitmapImage bitmap && bitmap.UriSource != null)
{
bitmap.ImageOpened += BitmapImageOpened;
bitmap.ImageFailed += BitmapImageFailed;
}
else
{
BeginFadeInAnimation();
}
}
tcs.TrySetResult(null);
}
catch (Exception ex)
{
tcs.TrySetException(ex);
}
}
#if UWP
if (!await Image.Dispatcher.TryRunAsync(CoreDispatcherPriority.Low, LoadAndSetImageSource))
#else
if (!Image.DispatcherQueue.TryEnqueue(DispatcherQueuePriority.Low, LoadAndSetImageSource))
#endif
{
tcs.TrySetCanceled();
}
await tcs.Task;
}
2025-01-05 10:31:15 +01:00
private void BeginFadeInAnimation()
{
2025-01-05 10:31:15 +01:00
var fadeInAnimation = new DoubleAnimation
2025-01-05 09:22:50 +01:00
{
From = 0d,
Duration = MapBase.ImageFadeDuration,
FillBehavior = FillBehavior.Stop
};
2025-01-05 10:31:15 +01:00
Storyboard.SetTarget(fadeInAnimation, Image);
2025-01-25 16:47:42 +01:00
Storyboard.SetTargetProperty(fadeInAnimation, nameof(UIElement.Opacity));
2025-01-05 09:22:50 +01:00
var storyboard = new Storyboard();
2025-01-05 10:31:15 +01:00
storyboard.Children.Add(fadeInAnimation);
2025-01-05 09:22:50 +01:00
storyboard.Begin();
}
private void BitmapImageOpened(object sender, RoutedEventArgs e)
{
var bitmap = (BitmapImage)sender;
bitmap.ImageOpened -= BitmapImageOpened;
bitmap.ImageFailed -= BitmapImageFailed;
2025-01-05 10:31:15 +01:00
BeginFadeInAnimation();
}
private void BitmapImageFailed(object sender, ExceptionRoutedEventArgs e)
{
var bitmap = (BitmapImage)sender;
bitmap.ImageOpened -= BitmapImageOpened;
bitmap.ImageFailed -= BitmapImageFailed;
Image.Source = null;
}
}
}