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.
I needed to get this done in a constraint layout with Picasso, so I munged together some of the above answers and came up with this solution (I already know the aspect ratio of the image I'm loading, so that helps):
Called in my activity code somewhere after setContentView(...)
In my XML
Note the lack of a constraintBottom_toBottomOf attribute. ImageLoader is my own static class for image loading util methods and constants.
(The answer was heavily modified after clarifications to the original question)
After clarifications:
This cannot be done in xml only. It is not possible to scale both the image and the
ImageView
so that image's one dimension would always be 250dp and theImageView
would have the same dimensions as the image.This code scales
Drawable
of anImageView
to stay in a square like 250dp x 250dp with one dimension exactly 250dp and keeping the aspect ratio. Then theImageView
is resized to match the dimensions of the scaled image. The code is used in an activity. I tested it via button click handler.Enjoy. :)
The xml code for the
ImageView
:Thanks to this discussion for the scaling code:
http://www.anddev.org/resize_and_rotate_image_-_example-t621.html
UPDATE 7th, November 2012:
Added null pointer check as suggested in comments
After searching for a day, I think this is the easiest solution:
The Below code make the bitmap perfectly with same size of the imageview. Get the bitmap image height and width and then calculate the new height and width with the help of imageview's parameters. That give you required image with best aspect ratio.
enjoy.
The Best solution that works in most cases is
Here is an example:
this can all be done using XML... the other methods seem pretty complicated. Anyway, you just set the height to what ever you want in dp, then set the width to wrap content or visa versa. Use scaleType fitCenter to adjust the size of the image.