GDI+ Complement, Exclude, and Union Methods in VB.NET
In this article I will explain about the the Complement, Exclude, and Union Methods in GDI+.
We saw the Region class methods in Table 6.1. Now let's use these methods in our applications.
The Complement method updates the portion of a Region object (specified by a rectangle or a region) that does not intersect the specified region. It takes an argument of type Rectangle, RectangleF, GraphicsPath, or Region and updates the region. Listing 6.7 creates two Region objects and draws rectangles with different pens. The Complement method updates only the portion of the first region that falls within the second region.
LISTING 6.7: Using the Complement method of the Region class
'Create a Graphics object
Dim g As Graphics = Me.CreateGraphics()
'Create two rectangles
Dim rect1 As New Rectangle(20, 20, 60, 80)
Dim rect2 As New Rectangle(50, 30, 60, 80)
'Create two regions
Dim rgn1 As New Region(rect1)
Dim rgn2 As New Region(rect2)
'Draw rectangles
g.DrawRectangle(Pens.Green, rect1)
g.DrawRectangle(Pens.Black, rect2)
'Complement can take Rectangle, RectangleF,
'Region, or GraphicsPath as an argument
rgn1.Complement(rect2)
g.FillRegion(Brushes.Blue, rgn1)
'Dispose of object
g.Dispose()
Figure 6.5 shows the output from Listing 6.7. Our code updates a portion of rgn1 that doesn't intersect with rgn2. It is useful when you need to update only a specific part of a region. For example, suppose you're writing a shooting game application and you program updates the targets only after gunfire. In this scenario you need to update only the target region, not the entire form.
FIGURE 6.5: Complementing regions
FIGURE 6.6: Excluding regions
The Exclude method updates the part of a region that does not interact with the specified region or rectangle. Like Complement, Exclude takes an argument of type Rectangle, RectangleF, GraphicsPath, or Region and updates the region. Listing 6.8 creates two Region objects and draws rectangles with different pens, then call Exclude.
LISTING 6.8: Using the Exclude method of the Region class
Dim g As Graphics = e.Graphics
Dim rect1 As New Rectangle(20, 20, 60, 80)
Dim rect2 As New Rectangle(20, 20, 60, 80)
Dim rgn1 As New Region(rect1)
Dim rgn2 As New Region(rect2)
g.DrawRectangle(Pens.Green, rect1)
g.DrawRectangle(Pens.Black, rect2)
rgn1.Exclude(rgn2)
g.FillRegion(Brushes.Blue, rgn1)
Figure 6.6 shows the output from Listing 6.8. Only the excluded part of the region is updated.
From the code Listing 6.8, replacing the line
rgn1.Exclude(rect2)
with
rgn1.Union(rgn2)
produces Figure 6.7, which updates the union of both regions (or rectangles). Like Exclude and Complement, the Union method can take Rectangle, RectangleF, GraphicsPath, or Region as an argument.
FIGURE 6.7: Applying Union or regions
Conclusion
Hope the article would have helped you in understanding the Complement, Exclude, and Union Methods in GDI+. Read other articles on GDI+ on the website.