Iris blur (blur around borders) effect using Win2D

Blur effects are getting pretty common in app designs, especially since iOS 7 started introducing them in some OS components like Control Center – and even the Windows 10 Start Menu uses the same effect to display a “frosted glass” look over the current background window.

Instead of a simple blur, which has been already explained by the awesome Deani Hansen, we are going to implement an iris blur (as Photoshop calls it; other resources call it “blur around borders”, and Instagram names it “tilt shift” with a radial blur in an UWP app by using the awesome Win2D library. It consists of a circular or ellipsoid area where the image shows focused, but everything else around it is defocused (or “blurred”) progressively, to give it a nice fading effect with no solid transition. So, let’s get started!

Approach

To achieve the result shown above, we are going to draw a blurred version of the image (in our case, a very beautiful one taken from Windows 10’s Spotlight backgrounds) over the original one – however, it will have a transparency mask applied so it can show a “hole” where there is no blurring. For additional artistic result, the hole won’t have clearly defined borders – instead we are going to use a radial gradient so it blends progressively over the non-blurred image. The following image describes how the blurred image with mask applied will be obtained:

Drawing the blurred image with a mask to obtain the overlay

We could store the resulting image in a CanvasRenderTarget instance and then draw it to our CanvasControl when needed – however, we can skip this intermediate step if we directly draw the original image and then the blurred one on top, just like the followind diagram shows:

Drawing the blur overlay over the original image and obtaining the final result

With all concepts clear, let’s go ahead with the implementation – I promise you it’s going to be really easy!

Implementation

Start by adding the Win2D.UWP library to your project from NuGet, and creating a CanvasControl in XAML. Hook up its CreateResources event and instantiate a new member variable of type CanvasRadialGradientBrush – along with loading the image we are going to draw. Our radial brush will have Colors.Transparent as a starting colour and Colors.Black as the ending one – the ending one could have been Colors.White or any other solid one though, as the layer will only take the alpha (transparency) component into account.

[code lang=”csharp”]
private void Canvas_CreateResources(Microsoft.Graphics.Canvas.UI.Xaml.CanvasControl sender, Microsoft.Graphics.Canvas.UI.CanvasCreateResourcesEventArgs args)
{
// Create instance of radial gradient brush; the center will be transparent and the extremes opaque black.
radialBrush = new CanvasRadialGradientBrush(sender, Colors.Transparent, Colors.Black);

// Load image to draw.
args.TrackAsyncAction(Task.Run(async () =>
{
image = await CanvasBitmap.LoadAsync(sender, new Uri("ms-appx:///SpotlightImage.png"));
}).AsAsyncAction());
}
[/code]

Next, we are going to wire up the Draw event – and perform all of our drawing there. Start by clearing the CanvasDrawingSession’s background to a colour of your choice, and then set the Center, RadiusX and RadiusY parameters of the radial gradient brush to meaningful values (in our case the center is always the center of the image/canvas, and the radius will be updated through a Slider control); then, draw the untouched image through CanvasDrawingSession.DrawImage:

[code lang=”csharp”]
// Start drawing session and clear background to white.
var session = args.DrawingSession;
args.DrawingSession.Clear(Colors.White);

// Set the center of the radial gradient as the center of the image.
radialBrush.Center = new System.Numerics.Vector2((float)(image.Size.Width / 2.0f), (float)(image.Size.Height / 2.0f));
// Assing gradient radius from slider control.
radialBrush.RadiusX = radialBrush.RadiusY = (float)BlurRadius.Value;

// Draw unaltered image first.
session.DrawImage(image, image.Bounds);
[/code]

Now comes the fun part – working with layers. The logic behind is that you create a layer by calling CanvasDrawingSession.CreateLayer and passing an opacity value, ICanvasBrush or CanvasGeometry and everything that is drawn from that point is affected by the opacity/mask/clipping area – pretty convenient, huh? Then, to stop using it, you just have to Dispose the CanvasActiveLayer – or instead, wrap everything inside an using block.

So, we are going to pass the CanvasRadialGradientBrush as the mask parameter, and then draw the image again but after applying a GaussianBlurEffect on it. This way, the masked, blurred version of the image will draw on top of the solid one, composing the desided effect:

[code lang=”csharp”]
// Create a layer, this way all elements drawn will be affected by a transparent mask
// which in our case is the radial gradient.
using (session.CreateLayer(radialBrush))
{
// Create gaussian blur effect.
using (var blurEffect = new GaussianBlurEffect())
{
// Set image to blur.
blurEffect.Source = image;
// Set blur amount from slider control.
blurEffect.BlurAmount = (float)BlurAmount.Value;
// Explicitly set optimization mode to highest quality, since we are using big blur amount values.
blurEffect.Optimization = EffectOptimization.Quality;
// This prevents the blur effect from wrapping around.
blurEffect.BorderMode = EffectBorderMode.Hard;
// Draw blurred image on top of the unaltered one. It will be masked by the radial gradient
// thus showing a transparent hole in the middle, and properly overlaying the alpha values.
session.DrawImage(blurEffect, 0, 0);
}
}
[/code]

I told you it was easy, wasn’t it? And just for reference, here is a video of how the effect looks in the sample project that complements this tutorial:

Source code

Get the source code for the entire sample project in the Win2D-Samples GitHub repository, under the IrisBlurWin2D subfolder.

Explicitly running a background task from the foreground in UWP apps

One of the multiple improvements that UWP has added to background task execution is the ability to directly invoke them from the app’s foreground window. This is extremely helpful if you are using it to update the appearance of the Live Tile using a XamlRenderingBackgroundTask – doing the same thing from the foreground isn’t trivial, the main reason being that the UIElement you want to render when calling RenderTargetBitmap.RenderAsync must be part of the current page’s visual tree (otherwise you will get an ArgumentException with the ambiguous message Value does not fall within the expected range). Before, it was solved by embedding it on the page’s XAML but with collapsed visibility – but thankfully, we don’t need to keep using this ugly hack!

In this brief tutorial we are going to learn how to use this new feature to our advantage, and call our background task whenever we want to instantly update the image of the Live Tile with new content – in this case, a text message.

Requisites

You should already have an existing UWP app project that has a Windows Runtime Component project with the background task code – preferably one derived from XamlRenderingBackgroundTask. If not, well – you can still follow the instructions and get the source code for the entire project (linked at the end of the post). Having used background tasks previously will make it easier too!

Adding the declaration to application manifest

First, we need to add a Background Tasks declaration to the manifest. This will tell the runtime that we are indeed using them in the app, and will arrange the appropriate permissions for it to be executed. Open the Package.appxmanifest file and navigate to the Declarations tab. There, we are going to add a new declaration of type Background Tasks, select General from Supported task types and type the name of the class that implements the background task (including full namespace) on the Entry point field (note that you may already have this declaration if you are already using launching the task from a timer or from a system event – if so, we could even get away without selecting the General type, but do it anyway just to be sure).

BackgroundTaskManifestPermissions

Implementing the background task

This is going to be a bit high level, since previous experience on background tasks is assumed. To begin with, we are going to create a custom UserControl that will hold the layout for the content of the tile – do it as you please, as we are going to use a coloured Border with a TextBlock inside for our sample. Then, instantiate it on the OnRun method of the task, and set its Width and Height – we are using 150×150, which is the size of the medium tile at 100% scale. You could detect the screen resolution and provide the scaled version accordingly – just don’t try rendering all of them, as it would use a lot of CPU and memory and the task would probably be cancelled!

[code lang=”csharp”]
// Create instance of the control that contains the layout of the Live Tile
MediumTileControl control = new MediumTileControl();
control.Width = TileWidth;
control.Height = TileHeight;
[/code]

Make any adjustments you like to the control before being rendered – like changing the background colour, the text to be shown (which is what we are going to do) or any images it may have. Customize it as necessary to reflect the correct information in the Live Tile.

[code lang=”csharp”]
// If we have received a message in the parameters, overwrite the default "Hello, Live Tile!" one
var triggerDetails = taskInstance.TriggerDetails as ApplicationTriggerDetails;
if (triggerDetails != null)
{
object tileMessage = null;
if (triggerDetails.Arguments.TryGetValue("Message", out tileMessage))
{
if (tileMessage is string)
{
control.Message = (string)tileMessage;
}
}
}
[/code]

Now, we are going to proceed to render the control to a bitmap and save it to a file. This is pretty standard stuff: we instantiate a RenderTargetBitmap, call RenderAsync passing our UserControl and desired final size, and open a file on the local storage for saving the bitmap. We will encode it to PNG format (so we keep transparency) using BitmapEncoder – and as a shortcut, we will create an intermediate SoftwareBitmap that will be filled with the pixels (via GetPixelsAsync) from the RenderTargetBitmap, and feed to the BitmapEncoder through SetSoftwareBitmap. Finally, we tell the BitmapEncoder to flush (via FlushAsync) the data to the file.

[code lang=”csharp”]
// Render the tile control to a RenderTargetBitmap
RenderTargetBitmap bitmap = new RenderTargetBitmap();
await bitmap.RenderAsync(control, TileWidth, TileHeight);

// Now we are going to save it to a PNG file, so create/open it on local storage
var file = await ApplicationData.Current.LocalFolder.CreateFileAsync(TileImageFilename, CreationCollisionOption.ReplaceExisting);
using (var stream = await file.OpenAsync(FileAccessMode.ReadWrite))
{
// Create a BitmapEncoder for encoding to PNG
BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, stream);

// Create a SoftwareBitmap from the RenderTargetBitmap, as it will be easier to save to disk
using (var softwareBitmap = new SoftwareBitmap(BitmapPixelFormat.Bgra8, TileWidth, TileHeight, BitmapAlphaMode.Premultiplied))
{
// Copy bitmap data
softwareBitmap.CopyFromBuffer(await bitmap.GetPixelsAsync());

// Encode and save to file
encoder.SetSoftwareBitmap(softwareBitmap);
await encoder.FlushAsync();
}
}
[/code]

For updating the Live Tile contents, we are going to use the excellent Notifications Extensions library – it will allow us to easily generate the XML content for the tile notification by creating statically typed objects. Finally, obtain a TileUpdater by calling TileUpdateManager.CreateTileUpdaterForApplication and call its Update method to send the notification to the tile.

[code lang=”csharp”]
// Use the NotificationsExtensions library to easily configure a tile update
TileContent mediumTileContent = new TileContent()
{
Visual = new TileVisual()
{
TileMedium = new TileBinding()
{
Content = new TileBindingContentAdaptive()
{
BackgroundImage = new TileBackgroundImage()
{
Overlay = 0,
Source = new TileImageSource("ms-appdata:///local/" + TileImageFilename),
}
}
}
}
};

// Clean previous update from Live Tile and update with the new parameters
var tileUpdater = TileUpdateManager.CreateTileUpdaterForApplication();
tileUpdater.Clear();
tileUpdater.Update(new TileNotification(mediumTileContent.GetXml()));
[/code]

Registering and calling the background task

Going back to our UWP app project, we need to register out task to it can be called when needed. Start by adding a member variable of type ApplicationTrigger to whichever place you are going to run your background task registration from – we are going to use the app’s MainPage but you could do it from its own service, etc.

Next, we need to register the task via a BackgroundTaskBuilder. Pretty standard stuff, except that we have to initialize the ApplicationTrigger member variable and pass it to the builder through SetTrigger. If the task was registered in a previous execution then we have to retrieve that registration (through BackgroundTaskRegistration.AllTasks) and obtain the reference to the trigger from there.

[code lang=”csharp”]
if (!BackgroundTaskRegistration.AllTasks.Any(reg => reg.Value.Name == TileRegistrationName))
{
// Configure task parameters
BackgroundTaskBuilder builder = new BackgroundTaskBuilder();
builder.TaskEntryPoint = typeof(TileUpdateTask).FullName;
builder.Name = TileRegistrationName;

// Remember to set an ApplicationTrigger so we can run it on demand later
this.backgroundTrigger = new ApplicationTrigger();
builder.SetTrigger(backgroundTrigger);
builder.Register();

MessageDialog infoDialog = new MessageDialog("Background task successfully registered.", "Info");
await infoDialog.ShowAsync();
}
else
{
// Fetch registration details and trigger if already existing
var registration = BackgroundTaskRegistration.AllTasks.FirstOrDefault(reg => reg.Value.Name == TileRegistrationName).Value as BackgroundTaskRegistration;
this.backgroundTrigger = registration.Trigger as ApplicationTrigger;

MessageDialog infoDialog = new MessageDialog("Background task registration data successfully retrieved.", "Info");
await infoDialog.ShowAsync();
}
[/code]

To wrap everything up, we now can call the task whenever we want (in the sample we are using a Button.Click event for this). We just have to call the method RequestAsync from the ApplicationTrigger we instantiated/retrieved previously – and the task will run, returning a code to tell us if it was able to launch, its execution was denied or any errors happened. Try it and watch the tile change in real time!

[code lang=”csharp”]
var taskParameters = new ValueSet();

// Send a custom message if we have typed one
if (!string.IsNullOrEmpty(MessageText.Text))
{
taskParameters.Add("Message", MessageText.Text);
}

// Fetch execution results and inform user accordingly
var taskResult = await backgroundTrigger.RequestAsync(taskParameters);
[/code]

Source code

You can grab it from the UWP-Samples repository at GitHub – it’s on the BackgroundTaskFromForeground folder. As you can see, from now on all smaller UWP samples and tutorials will be added to the same repository, hopefully making it easier to browse.