Rectangle with “sorted” edges

In some situation you would like to reassure that given Rectangle object have “top-down, left-right” order you can do it using following two snippets

this creates “normalized” copy of the given rectangle


		/**
		 * Takes rectangle as a parameter and returns new with sorted edges, i.e. (x=50, y=50, w=-100, h=-100) becomes (x=-50, y=-50, w=100, h=100). In other words it makes sure that rectangles top and left are smaller than bottom and right respectively.
		 * 
		 * @param	p_oRect
		 * @return
		 */
		protected function normalizeRect(p_oRect:Rectangle):Rectangle
		{
			var nr:Rectangle = new Rectangle();
				nr.top = Math.min(p_oRect.top, p_oRect.bottom);
				nr.bottom = Math.max(p_oRect.top, p_oRect.bottom);
				nr.left = Math.min(p_oRect.left, p_oRect.right);
				nr.right = Math.max(p_oRect.left, p_oRect.right);
				
			return nr;
		}

this modifies given rectangle directly

		/**
		 * Modifies the rectangle given in parameter and makes sure that edges are sorted, i.e. (x=50, y=50, w=-100, h=-100) becomes (x=-50, y=-50, w=100, h=100). In other words it makes sure that rectangles top and left are smaller than bottom and right respectively.
		 * This method works directly on the object without making a copy.
		 * @param	p_oRectRef
		 */
		protected function normalizeRectV2(p_oRectRef:Rectangle):void
		{
			var _nSwap:Number;
			_nSwap = p_oRectRef.top;
			p_oRectRef.top = Math.min(_nSwap, p_oRectRef.bottom);
			p_oRectRef.bottom = Math.max(_nSwap, p_oRectRef.top);
			
			_nSwap = p_oRectRef.left;
			p_oRectRef.left = Math.min(_nSwap, p_oRectRef.right);
			p_oRectRef.right = Math.max(_nSwap, p_oRectRef.left);
		}
This entry was posted in actionscript, flash and tagged , , . Bookmark the permalink.