Site icon Ryadel

Android: proportionally stretch an ImageView to fit the whole screen width while maintaining its aspect ratio

Proportional image resizing is a fairly common scenario while developing an Android app: there are a number of situations where you might want an image to stretch itself to horizontally fit the whole screen while keeping its original aspect ratio. You might think it should be easy: sadly, it's not.

The problem

Achieving this result in HTML would be extremely easy: we just need to set our image width to 100% and avoid to set any height, letting the browser doing the whole proportional resize job. Unfortunately, Android wears a different pair of shoes: the ImageView element containing your drawable resource (or downloaded file) requires a width and an height: we can give a fixed number in px, dp or other supported units, use the parent width with the match_parent command or use the actual image width using the wrap_content command: as we can see, proportional resize is not an option. We can achieve some decent results by setting android:layout_widthandroid:layout_height and android:scaleType to make them adapt to the container layout in the following way:

These values could work in your specific scenario, but they tend to give inconsistant results among different devices and, most importantly, among different image sizes/ratios.

The solution

Why should we use a plain ImageView? We can start by taking a look to this interesting post on StackOverflow showing how to extend a View in order to achieve a very similar result: then we can use that knowledge to build our own ImageView extension class. Here's an example of a ProportionalImageView which automatically scales its height according to its computed width keeping its original aspect ratio intact:

 

And this is how we can use it inside an XML layout:

Just remember to replace com.my.namespace with your app namespace and you should be fine.

Happy coding!

 

Exit mobile version