Search code examples
c#.netwpffillrectangles

Fill the outside of a rectangle


I would like to draw a rectangle in WPF (by code) and to fill the outside of it.

Here is an example :

enter image description here

The outside of the rectangle is grey (with low opacity), and the fill of the rectangle is trasparent.


Solution

  • You may also overlay your image with a semi-transparent Path element that uses a CombinedGeometry which combines one very large outer rectangle with an inner rectangle:

    <Grid>
        <Image Name="image" Source="C:\Users\Public\Pictures\Sample Pictures\Koala.jpg"/>
        <Path Fill="#AAFFFFFF">
            <Path.Data>
                <CombinedGeometry GeometryCombineMode="Xor">
                    <CombinedGeometry.Geometry1>
                        <RectangleGeometry Rect="0,0,10000,10000"/>
                    </CombinedGeometry.Geometry1>
                    <CombinedGeometry.Geometry2>
                        <RectangleGeometry x:Name="transparentRect" Rect="150,100,200,100"/>
                    </CombinedGeometry.Geometry2>
                </CombinedGeometry>
            </Path.Data>
        </Path>
    </Grid>
    

    You would now programatically adjust the Rect property of the transparentRect member as needed.