Add CCRect::unionWithRect

Add a new CCRect utility function called 'unionWithRect' which computes the minimum rectangle that contains the current rectangle and another given rectangle, similar to to the following .NET function: http://msdn.microsoft.com/en-us/library/ms521839.aspx
This commit is contained in:
Darragh Coy 2013-07-02 11:39:49 -07:00
parent 55202b978a
commit da58f035c5
2 changed files with 41 additions and 0 deletions

View File

@ -271,4 +271,44 @@ bool Rect::intersectsRect(const Rect& rect) const
rect.getMaxY() < getMinY());
}
Rect Rect::unionWithRect(const Rect & rect) const
{
float thisLeftX = origin.x;
float thisRightX = origin.x + size.width;
float thisTopY = origin.y + size.height;
float thisBottomY = origin.y;
if (thisRightX < thisLeftX)
{
std::swap(thisRightX, thisLeftX); // This rect has negative width
}
if (thisTopY < thisBottomY)
{
std::swap(thisTopY, thisBottomY); // This rect has negative height
}
float otherLeftX = rect.origin.x;
float otherRightX = rect.origin.x + rect.size.width;
float otherTopY = rect.origin.y + rect.size.height;
float otherBottomY = rect.origin.y;
if (otherRightX < otherLeftX)
{
std::swap(otherRightX, otherLeftX); // Other rect has negative width
}
if (otherTopY < otherBottomY)
{
std::swap(otherTopY, otherBottomY); // Other rect has negative height
}
float combinedLeftX = std::min(thisLeftX, otherLeftX);
float combinedRightX = std::max(thisRightX, otherRightX);
float combinedTopY = std::max(thisTopY, otherTopY);
float combinedBottomY = std::min(thisBottomY, otherBottomY);
return Rect(combinedLeftX, combinedBottomY, combinedRightX - combinedLeftX, combinedTopY - combinedBottomY);
}
NS_CC_END

View File

@ -245,6 +245,7 @@ public:
bool equals(const Rect& rect) const;
bool containsPoint(const Point& point) const;
bool intersectsRect(const Rect& rect) const;
Rect unionWithRect(const Rect & rect) const;
};