Search code examples
wpfxamlopacitymask

WPF OpacityMask weird behavior


I think I might have found a bug in WPF, or maybe I just don't fully understand how OpacityMasks work. As you can see on the first image, I have a diamond shaped path and a red circle. My goal is to make everything outside the diamond invisible. It works when the circle is inside the diamond shape, but whenever I move it to one of the corners, or outside the path, the OpacityMask seems to get stretched or distorted as you can see on the second image. My question is how can I make the OpacityMask work regardless of where the circle (or any other child element) is.

First image

Second Image

And this is my XAML code

<Grid Name="rootGrid">
    <Grid>
        <Grid.OpacityMask>
            <VisualBrush Visual="{Binding ElementName=path}"/>
        </Grid.OpacityMask>
        <Path Name="path" 
              Stretch="Fill" 
              Fill="Cyan" 
              StrokeThickness="1" 
              Stroke="GreenYellow" 
              Data="M 0,-1 1,0 0,1 -1,0 0,-1"/>
        <Ellipse Fill="Red" 
                 Margin="20,-17,22,61"/>
    </Grid>
</Grid>

Sorry for posting the images with links, but I don't have enough reputation to directly embed images.

Any help is appreciated!


Solution

  • Clemens solved my issue

    Set ViewportUnits="Absolute" on the VisualBrush, and then set its Viewport property to an appropriate rectangle, e.g. Viewport="0,0,100,100"