views:

601

answers:

1

I wrote a drawing function that draws various on-screen sprites. These sprites can only overlap up to a point. If they have to much overlap, they become too obscured. As a result I need to detect when these sprites are too much overlapped. Luckily, the problem is simplified in that the sprites can be treated as orthogonal rectangles. I'd like to know by how much these rectangles overlap. Right now, I just brute force it by testing each pixel in one rectangle to see if the other contains it. I count these and calculate the percentage overlap. I think there's probably a better, less brute force approach. What algorithm can I use to determine this?

I'm using wxwidgets.

+8  A: 

The results depends on how you define overlapping percentage, to keep it symmetric, I would code it like this:

double CalculatePercentOverlap(const wxRect& rect1, const wxRect& rect2)
{
  wxRect inter = rect1.Intersect(rect2);
  if (inter.IsEmpty())
    return 0;
  return (double)(inter.GetWidth()*inter.GetHeight()) * 2.0 /
    (double)(rect1.GetWidth()*rect1.GetHeight() + 
             rect2.GetWidth()*rect2.GetHeight());
}
jdehaan
Ahh you are brilliant. Did not know of the intersect function. Hey, people are getting upset about this looking like a homework question. I was too terse in my questioning. So, I'll probably delete it. Does deleting remove your points cause if it does i'll leave it. Thanks.
max
Do the wxRect objects handle rectangles that aren't parallel with the axes?
baumgart
@max - it would remove the points if his rep were recalculated, which will happen eventually
John Rasch
I'd leave this. Don't delete your question since somebody in the future could find this useful.
GMan
Also, you should prefer `static_cast` over C-style casts.
GMan
@max you can still edit your question, explaining what you meant. that will probably make people retract their -1 or upvote you
Johannes Schaub - litb
Should be noted that this function returns the percentage that the smaller rectangle is to the larger one. So the parameter order does not matter CalculatePercentageOverlay(wxRect(0,0,200,200), wxRect(0,0,50,50)) gives the same answer as CalculatePercentageOverlay(wxRect(0,0,50,50), wxRect(0,0,200,200))
max
@max sounds to me like a kind of special case (rects having a common corner) if you translate the smaller one to the negative coodinates, then you will have non trivial results. The "overlap" relation must be symmetric I think because there is no order R1 must relate to R2 as R2 to R1. Hope I understood you well :-)
jdehaan