Search code examples
c#wpfxamltransparencyopacitymask

Image Partial Transparency in WPF


I aligned two images one on top of the other,

and I am trying to set a transparent circle on the top one

For some reason, The EllipseGeometry Radius and Center Attributes have no effect.

Here is the XAML code

Thank you !

    <Viewbox Grid.Row="1" Stretch="Uniform" HorizontalAlignment="Center">
        <Image Name="BackImage" Width="640" Height="480" Source="Images/black.png"/>

    </Viewbox>
    <Viewbox Grid.Row="1" Stretch="Uniform" HorizontalAlignment="Center">
        <Image Name="FrontImage" Width="640" Height="480" Source="Images/white.png">
            <Image.OpacityMask>
                <DrawingBrush>
                    <DrawingBrush.Drawing>
                            <GeometryDrawing>
                                <GeometryDrawing.Pen>
                                    <Pen Thickness="0" Brush="Transparent" />
                                </GeometryDrawing.Pen>
                                <GeometryDrawing.Brush>
                                    <SolidColorBrush Color="Black" />
                                </GeometryDrawing.Brush>
                                <GeometryDrawing.Geometry>
                                        <EllipseGeometry Center="0,0" RadiusX="1" RadiusY="3"/>
                                </GeometryDrawing.Geometry>
                            </GeometryDrawing>
                    </DrawingBrush.Drawing>
                </DrawingBrush>
            </Image.OpacityMask>
        </Image>

    </Viewbox>

Here is what I try to acheieve.


Solution

  • In order to specify the GeometryDrawing in absolute coordinates, you have to set the Stretch property of the DrawingBrush to None.

    Moreover I would also recommend to put both images in one ViewBox.

    <Viewbox Stretch="Uniform" HorizontalAlignment="Center">
        <Grid>
            <Image Name="BackImage" Width="640" Height="480" Source="Images/black.png"/>
            <Image Name="FrontImage" Width="640" Height="480" Source="Images/white.png">
                <Image.OpacityMask>
                    <DrawingBrush Stretch="None">
                        <DrawingBrush.Drawing>
                            <GeometryDrawing Brush="Black">
                                <GeometryDrawing.Geometry>
                                    <EllipseGeometry Center="320,240"
                                                     RadiusX="150" RadiusY="100"/>
                                </GeometryDrawing.Geometry>
                            </GeometryDrawing>
                        </DrawingBrush.Drawing>
                    </DrawingBrush>
                </Image.OpacityMask>
            </Image>
        </Grid>
    </Viewbox>