Explorar o código

Add Clipped() method to Rectangle with some edge methods

- Added Clipped() which returns the rectangle clipped by
  the bounds of the passed-in rectangle.
- Also added some convenience methods for getting the
  locations of the rectangle edges. Helps bring a litte
  clarity and the max*() methods are especially useful
  as that is a not uncommon operation. I included
  the min*() methods for completeness so if you're
  working with edges your code will read consistent
  although I don't mind if people would rather they
  were deleted.
Nur Monson %!s(int64=12) %!d(string=hai) anos
pai
achega
4539277575
Modificáronse 2 ficheiros con 42 adicións e 0 borrados
  1. 28 0
      Core/Contents/Include/PolyRectangle.h
  2. 14 0
      Core/Contents/Source/PolyRectangle.cpp

+ 28 - 0
Core/Contents/Include/PolyRectangle.h

@@ -45,6 +45,34 @@ namespace Polycode {
 			*/						
 			void setRect(Number x, Number y, Number w, Number h);
 
+			/**
+			* Return a Rectangle formed by clipping this rectangle to the
+			* bounds of the passed rectangle.
+			*/
+			Rectangle Clipped(const Rectangle& rect) const;
+
+			/**
+			* Return the minimum X coordinate (the left edge).
+			*/
+			Number minX() const { return x; }
+
+			/**
+			* Return the maximum X coordinate (the right edge).
+			*/
+			Number maxX() const { return x + w; }
+
+			/**
+			 * Return the minimum Y coordinate (the top edge in a Y-down coordinate
+			 * system).
+			 */
+			Number minY() const { return y; }
+
+			/**
+			* Return the maximum Y coordinate (the bottom edge in a Y-down coordinate
+			* system).
+			*/
+			Number maxY() const { return y + h; }
+
 			/**
 			* X position
 			*/									

+ 14 - 0
Core/Contents/Source/PolyRectangle.cpp

@@ -21,6 +21,7 @@
 */
 
 #include "PolyRectangle.h"
+#include <algorithm> // for min/max
 
 using namespace Polycode;
 
@@ -30,3 +31,16 @@ void Rectangle::setRect(Number x, Number y, Number w, Number h) {
 	this->w = w;
 	this->h = h;		
 }
+
+Rectangle Rectangle::Clipped(const Rectangle& rect) const
+{
+	Rectangle result;
+
+	result.x = std::min(std::max(x, rect.x), rect.maxX());
+	result.w = std::max(std::min(maxX(), rect.maxX()), result.x) - result.x;
+
+	result.y = std::min(std::max(y, rect.y), rect.maxY());
+	result.h = std::max(std::min(maxY(), rect.maxY()), result.y) - result.y;
+
+	return result;
+}