Add blur to UWP ImageBrush

751 views Asked by At

I am trying to add a blur to a background image in my UWP app. I can add a blue to an Image with no issue using this code (I am actually applying this to a dynamically loaded image from the web at run time)

<Image Source="Assets/Photos/BisonBadlandsChillin.png"
       Width="100"
       Height="100">
       <interactivity:Interaction.Behaviors>
           <behaviors:Blur x:Name="blurry"
                             Value="10"
                             Duration="100"
                             Delay="0"
                             AutomaticallyStart="True" />
       </interactivity:Interaction.Behaviors>

However I want to add the blur to an image in a background, specifically to the background of a RelativePanel. The background of a RelativePanel however will only take ImageBrush in its content and whenever I try to add the same behaviour from the Community Toolkit to an ImageBrush I get an error:

Cannot add instance of type 'Microsoft.Toolkit.Uwp.UI.Animations.Behaviors.Blur' to a collection of type 'Microsoft.Xaml.Interactivity.BehaviorCollection'

Is there a way around this still using the Toolkit?

1

There are 1 answers

0
Nico Zhu On

The Blur animation behavior selectively blurs a XAML element by increasing or decreasing pixel size. But ImageBrush is not XAML element. So I think you can't add blur to imagebrush by it.

If you want add blur to uwp Imagebrush you can use Win2D. The GaussianBlurEffect can be used to create a very cool blur effect that can give us that Frosted Glass look in your app

private async void AddBrushToPanel(ImageBrush brush, Panel panel)
{
var file = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Assets/image.jpg"));
using (var stream = await file.OpenAsync(FileAccessMode.Read))
    {
        var device = new CanvasDevice();
        var bitmap = await CanvasBitmap.LoadAsync(device, stream);

        var renderer = new CanvasRenderTarget(device,
                                              bitmap.SizeInPixels.Width,
                                              bitmap.SizeInPixels.Height, bitmap.Dpi);
        using (var ds = renderer.CreateDrawingSession())
        {
            var blur = new GaussianBlurEffect();
            blur.BlurAmount = 5.0f;
            blur.Source = bitmap;
            ds.DrawImage(blur);
        }
        stream.Seek(0);
        await renderer.SaveAsync(stream, CanvasBitmapFileFormat.Jpeg);
        BitmapImage image = new BitmapImage();
        image.SetSource(stream);
        brush.ImageSource = image;
        panel.Background = brush;
    }
}