Scaling with Aspect Ratio
Thursday, 21st May 2015
I was very pleased with having built my first functional app, which shows one image and allows the user to select a menu option to change it for another. But the simple layout I have adopted keeps the image small, and displays it in the top left corner of the screen.
One of the things I'll want to do when writing a board game app is to scale the board to take up the available width of the screen, while maintaining its aspect ratio. I know the right place: the layout XML file, in its ImageView tag, has an attribute called android:layout_width. This can be set to "match_parent". So I tried this first, hoping that the corresponding android:layout_height would scale.
Sadly that wasn't enough. The image wasn't scaled or stretched, but merely centred horizontally; the ImageView had obviously been stretched but the bitmap inside had not. So a Google search later I came upon a solution at:
The first solution seems over-complicated for such a simple task, but the second solution is much more straightforward and does the job nicely. As well as changing android:layout_width as above, the following two attributes should be added to the ImageView tag:
android:adjustViewBounds="true" android:scaleType="fitCenter"
Android's developer reference at http://developer.android.com/ tells me that android:adjustViewBounds should be set "to true if you want the ImageView to adjust its bounds to preserve the aspect ratio of its drawable."
The same source tells me that android:scaleType has a range of values which merit further investigation. Sadly the developer's reference merely lists the values without descriptions, so I'll have to find out what they all do from another source or through experimentation.