Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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. :)

like image 259
MHV Avatar asked May 13 '18 05:05

MHV


People also ask

Which attribute is used to set an image in ImageView?

An ImageView control is used to display images in Android applications. An image can be displayed by assigning it to the ImageView control and including the android:src attribute in the XML definition of the control. Images can also be dynamically assigned to the ImageView control through Java code.

What is adjustViewBounds?

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.19-Dec-2012.


1 Answers

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.

like image 54
Raza Avatar answered Oct 13 '22 00:10

Raza