How to fit an image of random size to an ImageView
?
When:
- Initially
ImageView
dimensions are 250dp * 250dp - The image's larger dimension should be scaled up/down to 250dp
- The image should keep its aspect ratio
- The
ImageView
dimensions should match scaled image's dimensions after scaling
E.g. for an image of 100*150, the image and the ImageView
should be 166*250.
E.g. for an image of 150*100, the image and the ImageView
should be 250*166.
If I set the bounds as
<ImageView
android:id="@+id/picture"
android:layout_width="250dp"
android:layout_height="250dp"
android:layout_gravity="center_horizontal"
android:layout_marginTop="20dp"
android:adjustViewBounds="true" />
images fit properly in the ImageView
, but the ImageView
is always 250dp * 250dp.
Edited Jarno Argillanders answer:
How to fit Image with your Width and Height:
1) Initialize ImageView and set Image:
2) Now resize:
Edited
scaleImage
method: (you can replace EXPECTED bounding values)And .xml:
May not be answer for this specific question, but if someone is, like me, searching for answer how to fit image in ImageView with bounded size (for example,
maxWidth
) while preserving Aspect Ratio and then get rid of excessive space occupied by ImageView, then the simplest solution is to use the following properties in XML:Use this code:
I needed to have an ImageView and an Bitmap, so the Bitmap is scaled to ImageView size, and size of the ImageView is the same of the scaled Bitmap :).
I was looking through this post for how to do it, and finally did what I want, not the way described here though.
and then in onCreateView method
and then layoutImageView() code
And the result is that image fits inside perfectly, keeping aspect ratio, and doesn't have extra leftover pixels from ImageView when the Bitmap is inside.
Result
It's important ImageView to have wrap_content and adjustViewBounds to true, then setMaxWidth and setMaxHeight will work, this is written in the source code of ImageView,
try adding
android:scaleType="fitXY"
to yourImageView
.