XAML-Map-Control/MapControl/UWP/TileImageLoader.UWP.cs

80 lines
2.8 KiB
C#
Raw Normal View History

2017-08-04 21:38:58 +02:00
// XAML Map Control - https://github.com/ClemensFischer/XAML-Map-Control
// © 2020 Clemens Fischer
2017-08-04 21:38:58 +02:00
// Licensed under the Microsoft Public License (Ms-PL)
using System;
using System.Runtime.InteropServices.WindowsRuntime;
2017-08-04 21:38:58 +02:00
using System.Threading.Tasks;
using Windows.Storage;
using Windows.UI.Core;
using Windows.UI.Xaml.Media;
2017-08-04 21:38:58 +02:00
namespace MapControl
{
public partial class TileImageLoader
2017-08-04 21:38:58 +02:00
{
/// <summary>
2017-09-06 20:43:46 +02:00
/// Default StorageFolder where an IImageCache instance may save cached data,
/// i.e. ApplicationData.Current.TemporaryFolder.
2017-08-04 21:38:58 +02:00
/// </summary>
2017-09-06 20:43:46 +02:00
public static StorageFolder DefaultCacheFolder
{
get { return ApplicationData.Current.TemporaryFolder; }
}
2017-08-04 21:38:58 +02:00
/// <summary>
/// The IImageCache implementation used to cache tile images. The default is null.
/// </summary>
public static Caching.IImageCache Cache { get; set; }
private static async Task LoadCachedTileImageAsync(Tile tile, Uri uri, string cacheKey)
2017-08-04 21:38:58 +02:00
{
var cacheItem = await Cache.GetAsync(cacheKey).ConfigureAwait(false);
var buffer = cacheItem?.Buffer;
2017-08-04 21:38:58 +02:00
if (cacheItem == null || cacheItem.Expiration < DateTime.UtcNow)
2017-08-04 21:38:58 +02:00
{
2020-09-25 15:02:41 +02:00
var response = await ImageLoader.GetHttpResponseAsync(uri).ConfigureAwait(false);
if (response != null) // download succeeded
{
buffer = response.Buffer?.AsBuffer(); // may be null or empty when no tile available, but still be cached
await Cache.SetAsync(cacheKey, buffer, GetExpiration(response.MaxAge)).ConfigureAwait(false);
2017-08-04 21:38:58 +02:00
}
}
if (buffer != null && buffer.Length > 0)
2017-08-04 21:38:58 +02:00
{
await SetTileImageAsync(tile, () => ImageLoader.LoadImageAsync(buffer)).ConfigureAwait(false);
2017-08-04 21:38:58 +02:00
}
}
2017-08-04 21:38:58 +02:00
private static Task LoadTileImageAsync(Tile tile, TileSource tileSource)
{
return SetTileImageAsync(tile, () => tileSource.LoadImageAsync(tile.XIndex, tile.Y, tile.ZoomLevel));
2017-08-04 21:38:58 +02:00
}
private static async Task SetTileImageAsync(Tile tile, Func<Task<ImageSource>> loadImageFunc)
{
var tcs = new TaskCompletionSource<object>();
await tile.Image.Dispatcher.RunAsync(CoreDispatcherPriority.Low, async () =>
{
try
{
2020-09-25 15:02:41 +02:00
tile.SetImage(await loadImageFunc());
tcs.SetResult(null);
}
catch (Exception ex)
{
tcs.SetException(ex);
}
});
2020-09-25 15:02:41 +02:00
await tcs.Task.ConfigureAwait(false); // wait until image loading in the UI thread is completed
}
2017-08-04 21:38:58 +02:00
}
}