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. )
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).
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With