Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)

like image 645
emmby Avatar asked Jul 12 '11 19:07

emmby


People also ask

How do I fit a picture on android?

FIT_XY. Scale the image using Matrix. ScaleToFit#FILL . From XML, use this syntax: android:scaleType="fitXY" .

What is adjust view bounds in android?

android:adjustViewBounds—If set to true, the attribute adjusts the bounds of the ImageView control to maintain the aspect ratio of the image displayed through it. android:resizeMode—The resizeMode attribute is used to make a control resizable so we can resize it horizontally, vertically, or around both axes.


1 Answers

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

like image 173
roplacebo Avatar answered Sep 26 '22 14:09

roplacebo