Search code examples
c#wpfimageopacitymask

How to merge an image into the background along two edges?


I'm trying to create a stylish effect in my app that allows an image to sit in the top right hand corner with the left and bottom edges merging into the background colour using Image.OpacityMask. Something like:

enter image description here

This could be done using the following code, except Image.OpacityMask only allows for one child LinearGradientBrush:

    <Image Source="Images/poster.jpg" Width="300">
        <Image.OpacityMask>
            <LinearGradientBrush StartPoint="1, 0.5" EndPoint="0, 0.5">
                <GradientStop Color="Black" Offset="0.2" />
                <GradientStop Color="Transparent" Offset="1.0" />
            </LinearGradientBrush>
            <LinearGradientBrush StartPoint="0.5, 0" EndPoint="0.5, 1">
                <GradientStop Color="Black" Offset="0.2" />
                <GradientStop Color="Transparent" Offset="1.0" />
            </LinearGradientBrush>
        </Image.OpacityMask>
    </Image>

How can I create an Image.OpacityMask like this with valid code? I'm aware that there is a RadialGradientBrush, but this would blend the whole image, not just the left and bottom edges.


Solution

  • You could use two elements, e.g. an Image in a Border:

    <Border HorizontalAlignment="Right" VerticalAlignment="Top" Width="300">
        <Border.OpacityMask>
            <LinearGradientBrush StartPoint="1, 0.5" EndPoint="0, 0.5">
                <GradientStop Color="Black" Offset="0.2" />
                <GradientStop Color="Transparent" Offset="1.0" />
            </LinearGradientBrush>
        </Border.OpacityMask>
        <Image Source="Images/poster.jpg">
            <Image.OpacityMask>
                <LinearGradientBrush StartPoint="0.5, 0" EndPoint="0.5, 1">
                    <GradientStop Color="Black" Offset="0.2" />
                    <GradientStop Color="Transparent" Offset="1.0" />
                </LinearGradientBrush>
            </Image.OpacityMask>
        </Image>
    </Border>