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

82 lines
2.5 KiB
C#
Raw Normal View History

2017-09-05 20:57:17 +02:00
// XAML Map Control - https://github.com/ClemensFischer/XAML-Map-Control
// © 2017 Clemens Fischer
// Licensed under the Microsoft Public License (Ms-PL)
using System;
using System.Diagnostics;
2017-10-08 17:35:07 +02:00
using System.IO;
2017-09-05 20:57:17 +02:00
using System.Threading.Tasks;
2017-10-08 17:35:07 +02:00
using Windows.Storage;
2017-09-05 20:57:17 +02:00
using Windows.Storage.Streams;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Media.Imaging;
using Windows.Web.Http;
using Windows.Web.Http.Headers;
namespace MapControl
{
public partial class TileSource
{
/// <summary>
/// The HttpClient instance used when image data is downloaded from a web resource.
/// </summary>
public static HttpClient HttpClient { get; set; } = new HttpClient();
/// <summary>
2017-10-08 17:35:07 +02:00
/// Check HTTP response headers for tile availability, e.g. X-VE-Tile-Info=no-tile
2017-09-05 20:57:17 +02:00
/// </summary>
public static bool TileAvailable(HttpResponseHeaderCollection responseHeaders)
{
string tileInfo;
return !responseHeaders.TryGetValue("X-VE-Tile-Info", out tileInfo) || tileInfo != "no-tile";
}
2017-10-08 17:35:07 +02:00
protected async Task<ImageSource> LoadLocalImageAsync(Uri uri)
2017-09-05 20:57:17 +02:00
{
2017-10-08 17:35:07 +02:00
var path = uri.IsAbsoluteUri ? uri.LocalPath : uri.OriginalString;
if (!await Task.Run(() => File.Exists(path)))
{
return null;
}
2017-09-05 20:57:17 +02:00
2017-10-08 17:35:07 +02:00
var file = await StorageFile.GetFileFromPathAsync(path);
2017-09-05 20:57:17 +02:00
2017-10-08 17:35:07 +02:00
using (var stream = await file.OpenReadAsync())
2017-09-05 20:57:17 +02:00
{
2017-10-08 17:35:07 +02:00
var bitmapImage = new BitmapImage();
await bitmapImage.SetSourceAsync(stream);
return bitmapImage;
}
}
protected async Task<ImageSource> LoadHttpImageAsync(Uri uri)
{
using (var response = await HttpClient.GetAsync(uri))
{
if (!response.IsSuccessStatusCode)
{
Debug.WriteLine("TileSource: {0}: {1} {2}", uri, (int)response.StatusCode, response.ReasonPhrase);
}
else if (TileAvailable(response.Headers))
2017-09-05 20:57:17 +02:00
{
2017-10-08 17:35:07 +02:00
using (var stream = new InMemoryRandomAccessStream())
2017-09-05 20:57:17 +02:00
{
2017-10-08 17:35:07 +02:00
await response.Content.WriteToStreamAsync(stream);
stream.Seek(0);
2017-09-05 20:57:17 +02:00
2017-10-08 17:35:07 +02:00
var bitmapImage = new BitmapImage();
await bitmapImage.SetSourceAsync(stream);
2017-09-05 20:57:17 +02:00
2017-10-08 17:35:07 +02:00
return bitmapImage;
2017-09-05 20:57:17 +02:00
}
}
}
2017-10-08 17:35:07 +02:00
return null;
2017-09-05 20:57:17 +02:00
}
}
}