Search code examples
androidandroid-layoutimageviewscalecentering

How can I scale an image up and centre it at the bottom of its container?


I'm trying to make a very simple layout with the following properties:

  • Just contains a single image that should be:
    • Scaled up as much as possible while maintaining its original aspect ratio
    • Horizontally centred
    • At the bottom of its container

Here's an example of what it should look like:

portrait view showing image centred at the bottom but scaled uplandscape view showing image centred at the bottom but scaled up

I can get it to scale up and centre horizontally and vertically by setting the image to match_parent width and height and specifying scaleType of fitCentre. I could also get it to align to the bottom-right by using fitEnd.

I tried using RelativeLayout to centre it at the bottom, but I could only get this to work if I set the image's width and height to wrapContent, which caused it to not scale up.

Here's a sample layout to use as a starting point:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_gravity="bottom|center_horizontal"
        android:scaleType="fitStart"
        android:src="@drawable/abc_ic_search" />

</RelativeLayout>

Solution

  • Try this:

    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent">
    
        <ImageView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:scaleType="fitCenter"
                android:src="@drawable/abc_ic_search"
                android:adjustViewBounds="true"
                android:layout_alignParentBottom="true"/>
    
    </RelativeLayout>