Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding the overlapping area of two rectangles (in C#)

Edit:

Simple code I used to solve the problem in case anyone is interested (thanks to Fredrik):

    int windowOverlap(Rectangle rect1, Rectangle rect2)
    {
        if (rect1.IntersectsWith(rect2))
        {
            Rectangle overlap = Rectangle.Intersect(rect1, rect2);
            if (overlap.IsEmpty)
                return overlap.Width * overlap.Height;
        }

        return 0;
    }

Original Question:

I'd like to know a quick and dirty way to check if two rectangles overlap and if they do calculate the area of the overlap. For curiosities sake I'm interested in the case where 1) all the lines in both rectangles are either vertical or horizontal or 2) the general case for any two rectangles, but the only answer I really need is case 1.

I'm thinking along the lines of:

double areaOfOverlap( Rect A, Rect B)
{
    if ( A.Intersects(B) )
    {
        // calculate area
        // return area
    }

    return 0;
}

For A.Intersects() I was thinking of using the separating axis test, but if the rectangles have only horizontal and vertical lines is there an even simpler (faster) way to check?

And for calculating the area where they intersect is there an quick way to do it if the rectangles only horizontal and vertical lines?

Finally, this is unrelated to the question but I'd appreciate any advice someone may have on a good book / webpage where I could review the math for computer graphics. I've been out of college for a while and feel like I'm forgetting everything :)! Anyone else have that problem?

( NOTE: I found this question different than this which seems more complicated and doesn't directly answer the question. )

like image 607
Evan Avatar asked Oct 11 '09 17:10

Evan


People also ask

How do you check if two rectangles overlap with each other in C++?

Find if two rectangles overlap using C++. We know that a rectangle can be represented using two coordinates, the top left corner, and the bottom right corner. Suppose there are two rectangles, we have to check whether these two overlap or not. There are four coordinate points (l1, r1) and (l2, r2).

What is the area of overlap?

The OverlapArea function is a Spatial Numeric measurement that calculates the total area (or length or count) of overlap between features in the current layer and features in the target layer. Results are provided in map units.


1 Answers

Maybe I misinterpret your question, but doesn't the Rectangle.Intersect method do the job? It returns the intersecting area, and then you can easily calculate the area of it.

like image 81
Fredrik Mörk Avatar answered Sep 20 '22 14:09

Fredrik Mörk