diff --git a/src/Intervention/Image/Size.php b/src/Intervention/Image/Size.php index b559588e..fe5e3219 100644 --- a/src/Intervention/Image/Size.php +++ b/src/Intervention/Image/Size.php @@ -109,13 +109,26 @@ class Size public function fit(Size $size) { - $width = $size->getRatio() <= 1 ? null : $this->width; - $height = $size->getRatio() > 1 ? null : $this->height; + $auto_width = clone $size; + $auto_height = clone $size; - $size->resize($width, $height, function ($constraint) { + // create size with auto width + $auto_width->resize(null, $this->height, function ($constraint) { $constraint->aspectRatio(); }); + // create size with auto height + $auto_height->resize($this->width, null, function ($constraint) { + $constraint->aspectRatio(); + }); + + // decide which version to use + if ($auto_height->fitsInto($this)) { + $size = $auto_height; + } else { + $size = $auto_width; + } + $this->align('center'); $size->align('center'); $size->setPivot($this->relativePosition($size)); @@ -123,6 +136,11 @@ class Size return $size; } + public function fitsInto(Size $size) + { + return ($this->width <= $size->width) && ($this->height <= $size->height); + } + public function align($position, $offset_x = 0, $offset_y = 0) { switch (strtolower($position)) { diff --git a/tests/SizeTest.php b/tests/SizeTest.php index 66094b84..22cec778 100644 --- a/tests/SizeTest.php +++ b/tests/SizeTest.php @@ -292,6 +292,44 @@ class SizeTest extends PHPUnit_Framework_TestCase $this->assertEquals(300, $fitted->height); $this->assertEquals(50, $fitted->pivot->x); $this->assertEquals(0, $fitted->pivot->y); + + $box = new Size(600, 800); + $fitted = $box->fit(new Size(100, 100)); + $this->assertEquals(600, $fitted->width); + $this->assertEquals(600, $fitted->height); + $this->assertEquals(0, $fitted->pivot->x); + $this->assertEquals(100, $fitted->pivot->y); + } + + public function testFitsInto() + { + $box = new Size(800, 600); + $fits = $box->fitsInto(new Size(100, 100)); + $this->assertFalse($fits); + + $box = new Size(800, 600); + $fits = $box->fitsInto(new Size(1000, 100)); + $this->assertFalse($fits); + + $box = new Size(800, 600); + $fits = $box->fitsInto(new Size(100, 1000)); + $this->assertFalse($fits); + + $box = new Size(800, 600); + $fits = $box->fitsInto(new Size(800, 600)); + $this->assertTrue($fits); + + $box = new Size(800, 600); + $fits = $box->fitsInto(new Size(1000, 1000)); + $this->assertTrue($fits); + + $box = new Size(100, 100); + $fits = $box->fitsInto(new Size(800, 600)); + $this->assertTrue($fits); + + $box = new Size(100, 100); + $fits = $box->fitsInto(new Size(80, 60)); + $this->assertFalse($fits); } /**