How to scale and centre a drawable inside layer-list android?

Kai picture Kai · Oct 27, 2016 · Viewed 9.4k times · Source

I'm trying to center a drawable image with some padding on either side to use as a splash screen logo. The problem is it's either stretched across the entire screen or ignores any padding if I use gravity.

<?xml version="1.0" encoding="utf-8"?>

<item
    android:drawable="@color/grey_3"/>

<item android:gravity="top|center_horizontal|center_vertical" android:drawable="@drawable/zc_logo_r"
      android:top="100dp"
      android:left="200dp"
      android:right="200dp"
      android:layout_margin="100dp"
    >
</item>

I've tried using a bitmap, android:gravity="fill_horizontal" and various other suggestions on SO with the same result.

How can I scale and center the image in my xml?

Answer

Kai picture Kai · Oct 28, 2016

As a reference, if you come across the same issue, I solved it with a square image in drawable folders (i.e. hdpi, mdpi, xhpi, xxhpi and xxxhdpi) instead of resizing a rectangular image which was too big in size and gets distorted.

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@color/grey_3"/>
    <item android:gravity="center">
          <bitmap android:src="@drawable/splash_logo"/>
    </item>
</layer-list>