Scale an image up to fill entire ImageView in Android

I'd like to scale an image up to take up the entire size of an ImageView. This is subtly different than using scaleType=fit_center because fit_center will leave bands around the image if the image aspect ratio does not exactly match the ImageView's aspect ratio. Instead, I would like the image to get centered and scaled up to completely fill the enclosing view, with any excess chopped off.

I'm able to accomplish this by computing my own custom image matrix during onCreate():

final Display display = getWindowManager().getDefaultDisplay();
final float screenWidth = display.getWidth();
final float screenHeight = display.getHeight();
final float imageWidth = splashView.getDrawable().getIntrinsicWidth();
final float imageHeight = splashView.getDrawable().getIntrinsicHeight();
final Matrix splashMatrix = new Matrix();
final float scale = Math.max(screenHeight/imageHeight,screenWidth/imageWidth);
splashMatrix.postScale( scale, scale );
splashView.setImageMatrix(splashMatrix);

This works fine, but it seems like there must be an easier away. Does anyone know of a way to scale up an image in an ImageView while both preserving the aspect ratio of the image and fully filling in the ImageView?

(Note: in my case my ImageView is taking up the full screen, so I use getWindowManager().getDisplay() to find the desired image size. You can't use splashView.getWidth()/getHeight() because the view hasn't been laid out yet and doesn't have a size)

93645 次浏览

You can use android:scaleType="centerCrop". Keeps the aspect ratio and scales the image just like you want it.

For more information please go through the below link

http://developer.android.com/reference/android/widget/ImageView.html#attr_android:scaleType

In some cases all you need is

android:adjustViewBounds="true"
imageView.setScaleType(ImageView.ScaleType.FIT_XY);

This worked for me to fit the image inside the whole image view, plus it make sense that it says "ScaleType.FIT_XY" to fit the X and Y axis of the imageView.

From the xml file it would be:

android:scaleType="fitXY"

I am very late but hope it helps in the future. Here is my solution to how to stretch the image to full screen or image view without scaleType="fitXY" as it causes damage to the image. Use the following library.

[A simple imageview which scales the width or height aspect with the given ratio] https://github.com/santalu/aspect-ratio-imageview

To Find the aspect ratio of the device screen use the following Code.

DisplayMetrics metrics =this.getResources().getDisplayMetrics();
float ratio = ((float)metrics.heightPixels / (float)metrics.widthPixels);

you must set android:scaleType="centerCrop" to fill entire screen but you noticed that scaletype property worked together with android:layout_width and android:layout_height property. you must set to match_parent