From acfb2b7484d98d95a20ad21820c6c922b4e7cdb9 Mon Sep 17 00:00:00 2001 From: Patrick Walton Date: Fri, 14 Nov 2014 19:07:28 -0800 Subject: [PATCH] Add a method to transform a point and a rect via an affine transformation --- src/matrix2d.rs | 23 ++++++++++++++++++++--- src/rect.rs | 5 +++++ 2 files changed, 25 insertions(+), 3 deletions(-) diff --git a/src/matrix2d.rs b/src/matrix2d.rs index 7ed91d3..3afeb20 100644 --- a/src/matrix2d.rs +++ b/src/matrix2d.rs @@ -7,6 +7,10 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use point::Point2D; +use rect::Rect; +use size::Size2D; + use std::num::{One, Zero}; pub struct Matrix2D { @@ -15,7 +19,7 @@ pub struct Matrix2D { m31: T, m32: T } -impl + Clone + Mul + One + Zero> Matrix2D { +impl Matrix2D where T: Add + Clone + Mul + One + PartialOrd + Sub + Zero { pub fn new(m11: T, m12: T, m21: T, m22: T, m31: T, m32: T) -> Matrix2D { Matrix2D { m11: m11, m12: m12, @@ -53,14 +57,27 @@ impl + Clone + Mul + One + Zero> Matrix2D { _0.clone(), _1.clone(), _0.clone(), _0.clone()); } - + pub fn to_array(&self) -> [T, ..6] { [ self.m11.clone(), self.m12.clone(), self.m21.clone(), self.m22.clone(), self.m31.clone(), self.m32.clone() ] - } + } + #[inline] + pub fn transform_point(&self, point: &Point2D) -> Point2D { + Point2D(self.m11 * point.x + self.m21 * point.y + self.m31, + self.m21 * point.x + self.m22 * point.y + self.m32) + } + + #[inline] + pub fn transform_rect(&self, rect: &Rect) -> Rect { + let upper_left = self.transform_point(&rect.origin); + let lower_right = self.transform_point(&rect.max_point()); + Rect(upper_left.clone(), + Size2D(lower_right.x - upper_left.x, lower_right.y - upper_left.y)) + } } diff --git a/src/rect.rs b/src/rect.rs index 348f86e..556ed57 100644 --- a/src/rect.rs +++ b/src/rect.rs @@ -63,6 +63,11 @@ impl + Sub> Rect { self.origin.y.clone() } + #[inline] + pub fn max_point(&self) -> Point2D { + Point2D(self.max_x(), self.max_y()) + } + #[inline] pub fn intersection(&self, other: &Rect) -> Option> { if !self.intersects(other) {