14
votes

I want to scale an image in an ImageView in the following way. The ImageView has some dimensions Width (W) and Height (H). The image I'm putting into the image view could be smaller or bigger than WxH. I want it to scale while preserving aspect ratio to fill WxH space.

It seems like the closest thing to what I want is android:scaleType="centerInside", but what I'm seeing is that if the image is smaller than WxH, it will put a small-unscaled version of that image in the center of the ImageView (like the documentation says), but I want it to scale it to "fit", while showing the entire image, and stretching it to the maximum possible size of the container without cropping anything. In other words, stretch preserving aspect ratio until either the width or the height bumps into the edge of the container (ImageView).

This seems like an obvious thing to want to do, but I can't get it to work this way!!!

1
did you try android:scaletype="fitXY" ??Houcine
yes, but that doesn't preserve aspect ratio.user645402

1 Answers

15
votes

From the Android docs...

public static final Matrix.ScaleToFit CENTER

Compute a scale that will maintain the original src aspect ratio, but will also ensure that src fits entirely inside dst. At least one axis (X or Y) will fit exactly. The result is centered inside dst.

The XML attribute for this is...

android:scaleType="fitCenter"