I have an image which is smaller than the container I would like it to fit inside of. I would like the image to stretch, keeping it's aspect ratio, to it's largest possible size.
To illustrate this problem:
<ImageView android:layout_width="match_parent"
android:layout_height="wrap_content"
android:src="@drawable/thumbnail"
android:scaleType="fitXY"
android:adjustViewBounds="true"/>
The ImageView
above would be stretched to fill the width of the container. The @drawable
it contained would also stretch along the x axis to fit the width of ImageView
which is perfect. The problem however is that the dimension labelled wrap_content
, in this case height, remains the same size as the @drawable
s initial height.
I have read the documentation regarding ScaleType here and can't find the answer there.
The following image describes the above code:
Current behaviour Desired Behaviour
Edit
An ImageView
given scaleType="fitCenter"
will accurately expand/shrink the @drawable
inside of it to grow as large as possible while retaining it's aspect ratio.
The ImageView
s dimensions are defined before the @drawable
is scaled in any way. The ImageView
dimensions are not effected by scaling of it's contained @drawable
.
Best Answer
XML
The only solution to this in XML is to use
"match_parent"
or a discrete maximum value instead of"wrap_content"
where possible. This will ensure theImageView
is the correct size, which will then meaning addingscaleType="fitCenter"
will ensure the@drawable
will then scale correctly.Programatically
It's ugly, but you can resize the ImageView after it's dimensions have been given discrete values:
EDIT