Search code examples
c#uwpwin2dxaml-composition

how to apply mask to CompositionBrush


<Grid>
    <Image x:Name="BackgroundImage" Source="/Assets/background.png" />
    <Rectangle x:Name="ClippingRect" Margin="50" Fill="#30f0" />
</Grid>

How do I apply alpha mask, or clipping mask, so everything except the rectangle will be blurred?

I do the usual: GraphicsEffect->EffectFactory->Brush->Set to SpriteVisual

 var graphicsEffect = new BlendEffect
 {
     Mode = BlendEffectMode.Multiply,
     Background = new ColorSourceEffect
     {
         Name = "Tint",
         Color = Windows.UI.Color.FromArgb(50,0,255,0),
     },

     Foreground = new GaussianBlurEffect()
     {
         Name = "Blur",
         Source =  new CompositionEffectSourceParameter("Backdrop"),
         BlurAmount = (float)20,
         BorderMode = EffectBorderMode.Hard,
     }
 };

 var blurEffectFactory = _compositor.CreateEffectFactory(graphicsEffect,
     new[] { "Blur.BlurAmount", "Tint.Color" });

 var _brush = blurEffectFactory.CreateBrush();
 _brush.SetSourceParameter("Backdrop", _compositor.CreateBackdropBrush());

 var blurSprite = _compositor.CreateSpriteVisual();
 blurSprite.Size = new Vector2((float)BackgroundImage.ActualWidth, (float)BackgroundImage.ActualHeight);
 blurSprite.Brush = _brush;
 ElementCompositionPreview.SetElementChildVisual(BackgroundImage, blurSprite);

enter image description here


Solution

  • In Creators update, I can create class derived from XamlCompositionBrushBase and the apply it to the xaml element, so it does the blurring:

    <Grid>
        <Image x:Name="BackgroundImage" Source="/Assets/background.png" />
        <Path>
           <Path.Fill>
              <local:BlurTintBrush BlurRadius="5" TintColor="Black" TintOpacity="0.7" />
           </Path.Fill>
           <Path.Data>
               <GeometryGroup>
                   <RectangleGeometry x:Name="ImageGeometry" Rect="0,0,1027,768" /
                   <RectangleGeometry x:Name="CropGeometry" Rect="50,50,25,25" />
               </GeometryGroup>
           </Path.Data>
        </Path>
    </Grid>