Question

For some kind of mask dialog I want to be able to invert a geometry in C#. For example I would like to invert a rectange. I've got this working for filled rectangles but the same doesn't work for non filled ones.

For example if I have this rectangle on a canvas:

rectangle

And I invert this rectangle with the following code:

            RectangleGeometry line = new RectangleGeometry(_myRectangle);

            RectangleGeometry geo = new RectangleGeometry(_myCanvasRectangle);                               

            PathGeometry intersect = Geometry.Combine(line, geo, GeometryCombineMode.Xor, null);

            drawingContext.DrawGeometry(
                new SolidColorBrush(Color.FromArgb(99, _myObjectColor.R, _myObjectColor.G, _myObjectColor.B)),
                new Pen(new SolidColorBrush(_myObjectColor), _myActualLineWidth),
                intersect
                );

I get the following result (where the gray region is the filled region)

filled rectangle

Does anybody how I could achieve a result where only the rectangle (the black line in the first image) is spared and the rest is returned (filled with gray)?

Thanks guys!

Was it helpful?

Solution

So I found the solution myself: It seems geometries under C# are always filled "shapes". But you can get the outline (even with desired stroke thickness !) by using the GetWidenedPathGeometry method! My example looks like this:

            RectangleGeometry outerRect = new RectangleGeometry(_myRectangle);
            RectangleGeometry geo = new RectangleGeometry(_myCanvasRectangle);
            PathGeometry outerRectLine = outerRect.GetWidenedPathGeometry(new Pen(new SolidColorBrush(Colors.White), _myActualLineWidth));

            PathGeometry intersect = Geometry.Combine(geo, outerRectLine, GeometryCombineMode.Exclude, null);

            drawingContext.DrawGeometry(
                new SolidColorBrush(System.Windows.Media.Color.FromArgb(99, _myObjectColor.R, _myObjectColor.G, _myObjectColor.B)),
                new System.Windows.Media.Pen(new SolidColorBrush(Colors.White), ActualLineWidth),
                intersect
                );

Hope this helps someone else!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top