Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Drawing: What is the best way to draw a polygon with a hole in the middle

Tags:

c#

wpf

drawing

gdi

I have a shape that is defined by an outer border and then an inner border. IF there is no inner boarder, the shape is solid. If there is an inner border I want the polygon/path to be defined only between the two borders; I don't want to draw the outside and then draw the inside in the background color.

For example, if I have a square defined by the following coordinates for the outside border:

{0,0}, {20, 0}, {20,20}, {0, 20}

Then that square which is 20x20 with its bottom left right corner on the origin. That shape then has a triangle cut out of the center:

{10,10}, {15,10}, {15,15}

How can I create a path that contains this shape using either WPF or GDI+?

like image 798
Carri Avatar asked Jan 20 '23 12:01

Carri


2 Answers

You can draw that shape with XAML: (The key is to use a CombinedGeometry with GeometryCombineMode="Exclude")

<Path Fill="Black">
    <Path.Data>
        <CombinedGeometry GeometryCombineMode="Exclude">
            <CombinedGeometry.Geometry1>
                <RectangleGeometry Rect="0,0,20,20"/>
            </CombinedGeometry.Geometry1>
            <CombinedGeometry.Geometry2>
                <PathGeometry>
                    <PathFigure StartPoint="10,10">
                        <LineSegment Point="15,10"/>
                        <LineSegment Point="15,15"/>
                    </PathFigure>
                </PathGeometry>
            </CombinedGeometry.Geometry2>
        </CombinedGeometry>
    </Path.Data>
</Path>
like image 200
Mårten Wikström Avatar answered Jan 22 '23 01:01

Mårten Wikström


In GDI+, you can use FillPath() or DrawPath() with FillModeAlternate.

There's an example pretty close to what you're asking for here.

like image 37
Jason Williams Avatar answered Jan 22 '23 03:01

Jason Williams