Skip to content

Commit

Permalink
Add inner_rect and outer_rect methods to Rect
Browse files Browse the repository at this point in the history
Closes #258
  • Loading branch information
pyfisch committed Jan 14, 2018
1 parent 22cdd6d commit d2ff23e
Showing 1 changed file with 50 additions and 0 deletions.
50 changes: 50 additions & 0 deletions src/rect.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ use scale::TypedScale;
use num::*;
use point::TypedPoint2D;
use vector::TypedVector2D;
use side_offsets::TypedSideOffsets2D;
use size::TypedSize2D;

use num_traits::NumCast;
Expand Down Expand Up @@ -220,6 +221,42 @@ where T: Copy + Clone + Zero + PartialOrd + PartialEq + Add<T, Output=T> + Sub<T
self.translate(&size.to_vector())
}

/// Calculate the size and position of an inner rectangle.
///
/// Subtracts the side offsets from all sides. The horizontal and vertical
/// offsets must not be larger than the original side length.
pub fn inner_rect(&self, offsets: TypedSideOffsets2D<T, U>) -> Self {
let rect = TypedRect::new(
TypedPoint2D::new(
self.origin.x + offsets.left,
self.origin.y + offsets.top
),
TypedSize2D::new(
self.size.width - offsets.horizontal(),
self.size.height - offsets.vertical()
)
);
debug_assert!(rect.size.width >= Zero::zero());
debug_assert!(rect.size.height >= Zero::zero());
rect
}

/// Calculate the size and position of an outer rectangle.
///
/// Add the offsets to all sides. The expanded rectangle is returned.
pub fn outer_rect(&self, offsets: TypedSideOffsets2D<T, U>) -> Self {
TypedRect::new(
TypedPoint2D::new(
self.origin.x - offsets.left,
self.origin.y - offsets.top
),
TypedSize2D::new(
self.size.width + offsets.horizontal(),
self.size.height + offsets.vertical()
)
)
}

/// Returns the smallest rectangle defined by the top/bottom/left/right-most
/// points provided as parameter.
///
Expand Down Expand Up @@ -481,6 +518,7 @@ pub fn rect<T: Copy, U>(x: T, y: T, w: T, h: T) -> TypedRect<T, U> {
mod tests {
use point::Point2D;
use vector::vec2;
use side_offsets::SideOffsets2D;
use size::Size2D;
use super::*;

Expand Down Expand Up @@ -657,6 +695,18 @@ mod tests {
assert!(rr.origin.y == 5);
}

#[test]
fn test_inner_outer_rect() {
let inner_rect: Rect<i32> = Rect::new(Point2D::new(20, 40), Size2D::new(80, 100));
let offsets = SideOffsets2D::new(20, 10, 10, 10);
let outer_rect = inner_rect.outer_rect(offsets);
assert_eq!(outer_rect.origin.x, 10);
assert_eq!(outer_rect.origin.y, 20);
assert_eq!(outer_rect.size.width, 100);
assert_eq!(outer_rect.size.height, 130);
assert_eq!(outer_rect.inner_rect(offsets), inner_rect);
}

#[test]
fn test_min_max_x_y() {
let p = Rect::new(Point2D::new(0u32, 0u32), Size2D::new(50u32, 40u32));
Expand Down

0 comments on commit d2ff23e

Please sign in to comment.