Scaling an image to max available width, keeping aspect ratio and avoiding ImageView extra space

Shlomi Schwartz picture Shlomi Schwartz · Jan 3, 2012 · Viewed 18.2k times · Source

I have this simple layout XML, and a green_square.png file which is 30X30 pixels

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

    <ImageView
        android:background="@color/red"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:adjustViewBounds="true"
        android:scaleType="fitStart"
        android:src="@drawable/green_square"/>

</LinearLayout>

What I'm trying to achieve is scaling the image to fill the parent width, keeping it's aspect ratio with no extra space of the ImageView.

I've added a red background to the ImageView just for reference of the extra space I want to avoid.

Here is my goal

Answer

Blucreation picture Blucreation · Mar 24, 2013
<ImageView
        android:id="@+id/game"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:scaleType="centerCrop"
        android:adjustViewBounds="true"
        android:src="@drawable/ic_game" 
        />

this works for me. Full width of parent and center crop to keep aspect ratio