From 19753b4563a5a2a15094e95c7ddc93dac92ce76b Mon Sep 17 00:00:00 2001 From: wangchuang <515497782@qq.com> Date: Mon, 22 May 2023 10:49:42 +0800 Subject: [PATCH] feat: ImageBrushLoader --- .../Pages/AttachedPropertiesPage.axaml | 34 ++++++++++++- AsyncImageLoader.Avalonia/ImageBrushLoader.cs | 48 +++++++++++++++++++ 2 files changed, 80 insertions(+), 2 deletions(-) create mode 100644 AsyncImageLoader.Avalonia/ImageBrushLoader.cs diff --git a/AsyncImageLoader.Avalonia.Demo/Pages/AttachedPropertiesPage.axaml b/AsyncImageLoader.Avalonia.Demo/Pages/AttachedPropertiesPage.axaml index 21ac4c5..7d7cf35 100644 --- a/AsyncImageLoader.Avalonia.Demo/Pages/AttachedPropertiesPage.axaml +++ b/AsyncImageLoader.Avalonia.Demo/Pages/AttachedPropertiesPage.axaml @@ -6,14 +6,44 @@ mc:Ignorable="d" d:DesignWidth="800" d:DesignHeight="450" x:Class="AsyncImageLoader.Avalonia.Demo.Pages.AttachedPropertiesPage"> + + + + Images from Internet - - + + + + + + + + + + + + + + + + + + + + + + Images from Assets (AvaloniaResource) diff --git a/AsyncImageLoader.Avalonia/ImageBrushLoader.cs b/AsyncImageLoader.Avalonia/ImageBrushLoader.cs new file mode 100644 index 0000000..41566f3 --- /dev/null +++ b/AsyncImageLoader.Avalonia/ImageBrushLoader.cs @@ -0,0 +1,48 @@ +using System; +using System.Reactive.Linq; +using AsyncImageLoader.Loaders; +using Avalonia; +using Avalonia.Media; + +namespace AsyncImageLoader { + public static class ImageBrushLoader { + public static IAsyncImageLoader AsyncImageLoader { get; set; } = new RamCachedWebImageLoader(); + static ImageBrushLoader() { + SourceProperty.Changed + .Where(args => args.IsEffectiveValueChange) + .Subscribe(args => OnSourceChanged((ImageBrush)args.Sender, args.NewValue.Value)); + } + + private static async void OnSourceChanged(ImageBrush sender, string? url) { + SetIsLoading(sender, true); + + var bitmap = url == null + ? null + : await AsyncImageLoader.ProvideImageAsync(url); + if (GetSource(sender) != url) return; + sender.Source = bitmap; + + SetIsLoading(sender, false); + } + + public static readonly AttachedProperty SourceProperty = AvaloniaProperty.RegisterAttached("Source", typeof(ImageLoader)); + + public static string? GetSource(ImageBrush element) { + return element.GetValue(SourceProperty); + } + + public static void SetSource(ImageBrush element, string? value) { + element.SetValue(SourceProperty, value); + } + + public static readonly AttachedProperty IsLoadingProperty = AvaloniaProperty.RegisterAttached("IsLoading", typeof(ImageLoader)); + + public static bool GetIsLoading(ImageBrush element) { + return element.GetValue(IsLoadingProperty); + } + + private static void SetIsLoading(ImageBrush element, bool value) { + element.SetValue(IsLoadingProperty, value); + } + } +} \ No newline at end of file