How to fit an image of random size to an ImageView?
When:
- Initially
ImageViewdimensions are 250dp * 250dp - The image’s larger dimension should be scaled up/down to 250dp
- The image should keep its aspect ratio
- The
ImageViewdimensions 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.
(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
ImageViewso that image’s one dimension would always be 250dp and theImageViewwould have the same dimensions as the image.This code scales
Drawableof anImageViewto stay in a square like 250dp x 250dp with one dimension exactly 250dp and keeping the aspect ratio. Then theImageViewis 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