Skip to content

Novis\Image\Image::Fit

How resized fits an image into the width and height you give it.

Image::Fit is declared in the class Novis\Image\Image.

You pass an Image::Fit to resized as fit. It decides what happens when the image and the box you give have a different shape:

  • Cover fills the whole box and cuts off what does not fit. This is the default.
  • Contain keeps the whole image inside the box. The result is exactly the box size, and the empty part is transparent.
  • Fill stretches the image to the box size. The shape of the image changes.
  • Inside keeps the whole image, and the result is no larger than the box. One side may be smaller.
  • Outside covers the box without cutting anything off. One side may be larger than the box.

With Cover, gravity chooses which part of the image is kept.

Examples

Five ways into one box

<?nvs
// Shows the size each `Image::Fit` gives when a wide image is resized into a square box.
use Novis\Image\Color;
use Novis\Image\Image;
class Size
{
public static function of(Image $image): string
{
var $raw = $image->raw();
return "{$raw->width} x {$raw->height}";
}
}
// The image is 400 by 200 pixels. The box is 100 by 100.
Image $wide = Image::create(400, 200, Color::hex('#336699'));
// `Inside` gives 100 x 50 and `Outside` gives 200 x 100. The other three give 100 x 100.
echo 'Cover: ', Size::of($wide->resized({ width: 100, height: 100, fit: Image::Fit::Cover })), "\n";
echo 'Contain: ', Size::of($wide->resized({ width: 100, height: 100, fit: Image::Fit::Contain })), "\n";
echo 'Fill: ', Size::of($wide->resized({ width: 100, height: 100, fit: Image::Fit::Fill })), "\n";
echo 'Inside: ', Size::of($wide->resized({ width: 100, height: 100, fit: Image::Fit::Inside })), "\n";
echo 'Outside: ', Size::of($wide->resized({ width: 100, height: 100, fit: Image::Fit::Outside })), "\n";
Output
Cover: 100 x 100
Contain: 100 x 100
Fill: 100 x 100
Inside: 100 x 50
Outside: 200 x 100