Search code examples
androidandroid-layoutandroid-image

How to handle image aspect ratio on different resolutions and rotation


What's the right and clean way to handle images aspect ratio?

In my app, if I rotate the screen, I lose the aspect ratio and my images appear ugly as hell - see these images comparing my app and Play Store - https://i.sstatic.net/8EzKO.jpg

This is how I'm doing:

<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:orientation="horizontal"
    android:layout_gravity="center" >

    <Button
        android:id="@+id/btnStark"
        android:layout_marginLeft="4dp"
        android:layout_marginRight="2dp"
        android:layout_width="fill_parent"
        android:layout_height="100dp"
        android:layout_weight="1"
        android:background="@drawable/stark"
        android:gravity="center|bottom"
        android:layout_gravity="top" />

    <Button
        android:id="@+id/btnLannister"
        android:layout_marginLeft="2dp"
        android:layout_marginRight="4dp"
        android:layout_width="fill_parent"
        android:layout_height="100dp"
        android:layout_weight="1"
        android:background="@drawable/stark"
        android:gravity="center|bottom"
        android:layout_gravity="top" />
</LinearLayout>

How should I handle the height? Should I set a fixed value? Or is there any way it automatically keeps the aspect ratio?

The image I'm using is 400x300 pixels


Solution

  • Consider using ImageViews instead of buttons - they can be clickable just like buttons. You can set how the images scale using the scaleType attribute.

    http://developer.android.com/reference/android/widget/ImageView.ScaleType.html

    For example, with CENTER_INSIDE:

    Scale the image uniformly (maintain the image's aspect ratio) so that both dimensions (width and height) of the image will be equal to or less than the corresponding dimension of the view (minus padding).

    So, something like:

    <ImageView
        android:id="@+id/btnStark"
        android:layout_marginLeft="4dp"
        android:layout_marginRight="2dp"
        android:layout_width="fill_parent"
        android:layout_height="100dp"
        android:layout_weight="1"
        android:src="@drawable/stark"
        android:scaleType="centerInside"
        android:gravity="center|bottom"
        android:layout_gravity="top" />
    

    A Lannister always pays his debts.