2

I'm using WPF opacitymask to 'cut out' the shape of an area that's animated. I noticed that by default, the opacitymask applies only to the content of a panel rather than to the whole panel.

Setting the background to transparent is a working solution as (apparently it forces the opacitymask to be stretched. It feels like a workaround however, so I'm curious if there's an 'intended' way to make the opacitymask stretch to the entire grid.

See below for example code and result:

<Window x:Class="Sandbox.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="400" Width="800">
<Window.Resources>
    <ImageBrush x:Key="SomeAlphaMaskBrush" ImageSource="https://upload.wikimedia.org/wikipedia/commons/thumb/7/70/Dog_silhouette.svg/1034px-Dog_silhouette.svg.png"></ImageBrush>
</Window.Resources>
<Grid Name="Container">
    <Grid.ColumnDefinitions>
        <ColumnDefinition/>
        <ColumnDefinition/>
    </Grid.ColumnDefinitions>
    <Grid Name="Container01" OpacityMask="{StaticResource SomeAlphaMaskBrush}" Background="Transparent">
        <!-- Container01 has a transparent background and it makes the OpacityMask stretch to the entire Container01 -->
        <Rectangle Margin="70" Fill="Black"/>
    </Grid>
    <Grid Grid.Column="1" Name="Container02" OpacityMask="{StaticResource SomeAlphaMaskBrush}">
        <!-- Container02 has no background, the opacitymask is applied only to its content -->
        <Rectangle Margin="70" Fill="Black"/>
    </Grid>
</Grid>

Resulting output here: Output

Tony
  • 16,527
  • 15
  • 80
  • 134
Daan Terra
  • 21
  • 2

1 Answers1

0

You can use ViewportUnits="Absolute" and VisualBrush property to set the desired OpacityMask rectangle:

<ImageBrush x:Key="SomeAlphaMaskBrush" ViewportUnits="Absolute" Viewport="0 0 20 20" ImageSource="https://upload.wikimedia.org/wikipedia/commons/thumb/7/70/Dog_silhouette.svg/1034px-Dog_silhouette.svg.png"/>
Dean Kuga
  • 11,878
  • 8
  • 54
  • 108