Android – Fitting image width to match parent and adjust height according to aspect ratio in ImageView

androidimageview

I have an ImageView in my xml –

<ImageView
    android:id="@+id/image"
    android:layout_centerHorizontal="true"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"                     
    android:layout_marginTop="10dp"
    android:layout_marginBottom="10dp"/>

I am using Glide library to fetch image from an url and set that into the ImageView.

All i want is to match the width of image with parent width and then adjust the height of image without affecting the aspect ratio.

if the image dimension is very less, it should be expanded to match parent width and if image dimension are more than screen size it should be shrinked to match parent width.

ImageView img = (ImageView) findViewById("image");
Glide.with(this).load("url here").into(img);

Which scaleType should i use ?
Is it possible in XML or it needs java code ?

Thanks in advance. 🙂

Best Answer

It is possible from the xml. I achieved it using the following code.

        <ImageView
        android:id="@+id/ivImage"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:scaleType="fitXY"
        android:adjustViewBounds="true"/>

Scale XY scales the image using FILL and adjust view bounds preserves the aspect ratio. I do not think you need center horizontal property.

After this I called a photo loader library to just download the image into the image view.