in reply to Detecting control placement constraints in dialog resources - rectangle overlap checking

A sub to detect overlap of two rectangles is not that hard, especially if you go the other way: eliminate all the possibilities on how not to overlap. The rectangles will not overlap if one is completely to the left of the other, or vice vera, nor if it's completely below the other, or vice versa. In any other circumstances, they must overlap. This code will do that. I do allow the rectangles to touch.
use List::Util qw(min max); sub rect_overlap { my($r1, $r2) = @_; # two rectangles, like [x1, y1, x2, y2] # r1 is on the left of r2 return 0 if max(@$r1[0, 2]) <= min(@$r2[0, 2]); # r2 is on the left of r1 return 0 if max(@$r2[0, 2]) <= min(@$r1[0, 2]); # r1 is below r2 return 0 if max(@$r1[1, 3]) <= min(@$r2[1, 3]); # r2 is below r1 return 0 if max(@$r2[1, 3]) <= min(@$r1[1, 3]); # they must overlap: return 1; } # some tests: use Test::Simple 'no_plan'; ok rect_overlap [10, 10, 30, 30], [20, 20, 40, 60]; # do ok !rect_overlap [10, 10, 30, 30], [20, 40, 40, 60]; # don't ok rect_overlap [10, 10, 30, 30], [15, 15, 20, 20]; # inside
  • Comment on Re: Detecting control placement constraints in dialog resources - rectangle overlap checking
  • Download Code