summaryrefslogtreecommitdiff
path: root/Xamarin.Forms.Platform.MacOS/ImageSourceHandlers.cs
blob: 7a73ace45dd400a52fe08ce679ee479ecc61d764 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
´╗┐using System.IO;
using System.Threading;
using System.Threading.Tasks;
using AppKit;

namespace Xamarin.Forms.Platform.MacOS
{
	public interface IImageSourceHandler : IRegisterable
	{
		Task<NSImage> LoadImageAsync(ImageSource imagesource, CancellationToken cancelationToken = default(CancellationToken),
			float scale = 1);
	}

	public sealed class FileImageSourceHandler : IImageSourceHandler
	{
		public Task<NSImage> LoadImageAsync(ImageSource imagesource,
			CancellationToken cancelationToken = default(CancellationToken), float scale = 1f)
		{
			NSImage image = null;
			var filesource = imagesource as FileImageSource;
			var file = filesource?.File;
			if (!string.IsNullOrEmpty(file))
				image = File.Exists(file) ? new NSImage(file) : null;
			return Task.FromResult(image);
		}
	}

	public sealed class StreamImagesourceHandler : IImageSourceHandler
	{
		public async Task<NSImage> LoadImageAsync(ImageSource imagesource,
			CancellationToken cancelationToken = default(CancellationToken), float scale = 1f)
		{
			NSImage image = null;
			var streamsource = imagesource as StreamImageSource;
			if (streamsource?.Stream == null) return null;
			using (
				var streamImage = await ((IStreamImageSource)streamsource).GetStreamAsync(cancelationToken).ConfigureAwait(false))
			{
				if (streamImage != null)
					image = NSImage.FromStream(streamImage);
			}
			return image;
		}
	}

	public sealed class ImageLoaderSourceHandler : IImageSourceHandler
	{
		public async Task<NSImage> LoadImageAsync(ImageSource imagesource,
			CancellationToken cancelationToken = default(CancellationToken), float scale = 1f)
		{
			NSImage image = null;
			var imageLoader = imagesource as UriImageSource;
			if (imageLoader != null && imageLoader.Uri != null)
			{
				using (var streamImage = await imageLoader.GetStreamAsync(cancelationToken).ConfigureAwait(false))
				{
					if (streamImage != null)
						image = NSImage.FromStream(streamImage);
				}
			}
			return image;
		}
	}
}