Android – how to fit image to width and keep the aspect ratio in android

androidandroid-imageviewandroid-layoutimageview

I have an ImageView with fixed height and width (say with width of 100dp and height of 50dp). I need to dynamically load an image to this image view.

I want this image to scale in a way that fills the ImageView's width but do keep the aspect ratio (I don't care if part of image is not visible due to height limit).

what I want is really similar to centerCrop, but I don't want my image to be centered vertically!

thanks in advance.

edit1:

here's my codes:

this is my layout. I want to set image for imageView with background id.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">

<ImageView
    android:id="@+id/background"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignTop="@+id/footer"
    android:layout_alignBottom="@id/footer"
    />

<RelativeLayout
    android:id="@+id/footer"
    android:layout_width="match_parent"
    android:layout_height="100dp">

</RelativeLayout>

note that imageView is bound to size of the second RelativeLayout:

    android:layout_alignTop="@+id/footer"
    android:layout_alignBottom="@id/footer"

Best Answer

first in your layout add

android:scaleType="matrix"

to your imageView.

then in your java code add this:

ackground.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {

            Bitmap backgroundBitmap = BitmapFactory.decodeResource(getResources(),
                    R.drawable.background_image);

            float imageRatio = (float) backgroundBitmap.getWidth() / (float) backgroundBitmap.getHeight();

            int imageViewWidth = background.getWidth();
            int imageRealHeight = (int) (imageViewWidth / imageRatio);

            Bitmap imageToShow = Bitmap.createScaledBitmap(backgroundBitmap, imageViewWidth, imageRealHeight, true);
            background.setImageBitmap(imageToShow);

        }
    });

I will break it down for you:

at the java code you create a Bitmap object with the desired width (your imageView width) and set it to your imageView. but you need to make your imageView scaleType to matrix to prevent android from automatically scaling it!

Related Topic