By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
460,022 Members | 1,354 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 460,022 IT Pros & Developers. It's quick & easy.

Find the intersection of two rectangles

P: n/a
Hi,

Can some body share the code to find the intersection of two
rectangles?

Thanks in advance

Nov 14 '05 #1
Share this Question
Share on Google+
3 Replies


P: n/a
ca********@hotmail.com wrote:
Hi,

Can some body share the code to find the intersection of two
rectangles?

Thanks in advance


You may want to look at alt.sources.wanted.

If two rectangles intersect, then at least one line
segment from one rectangle must have a point in common
with another line segment. This can be found algebraically.

--
Thomas Matthews

C++ newsgroup welcome message:
http://www.slack.net/~shiva/welcome.txt
C++ Faq: http://www.parashift.com/c++-faq-lite
C Faq: http://www.eskimo.com/~scs/c-faq/top.html
alt.comp.lang.learn.c-c++ faq:
http://www.comeaucomputing.com/learn/faq/
Other sites:
http://www.josuttis.com -- C++ STL Library book
http://www.sgi.com/tech/stl -- Standard Template Library

Nov 14 '05 #2

P: n/a
<ca********@hotmail.com> wrote in message
news:11**********************@z14g2000cwz.googlegr oups.com...
Can some body share the code to find the intersection of two
rectangles?

Unless the rectangles are axis-aligned, you're pretty much in
the general case of Convex Polygon Intersection (--> Google).

If your rectangles are given in 2D as Top,Left,Bottom,Right
coordinates, as typical for GUI programming, then it's simply:
intersect.Left = max(a.Left, b.Left);
intersect.Top = max(a.Top, b.Top);
intersect.Right = min(a.Right, b.Right );
intersect.Bottom = min(a.Bottom, b.Bottom);
And the intersection is empty unless
intersect.Right > intersect.Left
&& intersect.Bottom > intersect.Top
hth-Ivan
--
http://ivan.vecerina.com/contact/?subject=NG_POST <- email contact form
Nov 14 '05 #3

P: n/a
Assume :

Rect A and Rect B. Upper Left(ul) and Lower Right(lr) co-ords are
given. The following function will return true if they intersect.

int areIntersecting(Rect A, Rect B) {
return ( ! ( (A.ul.x > B.lr.x) || (B.ul.x > A.lr.x) || (A.ul.y
< B.lr.y) || (B.ul.y < A.lr.y))
}

You can obviously use DeMorgan's law to remove the negation operator.

Nov 14 '05 #4

This discussion thread is closed

Replies have been disabled for this discussion.