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

2

7

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?

Hitoshi answered 27/10, 2016 at 0:30 Comment(0)
H
8

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>
Hitoshi answered 28/10, 2016 at 4:34 Comment(2)
You'd better set gravity not for the item, but for the bitmap itself. Otherwise, it might be stretched on pre-Lollipop devicesKnack
This does not solve the issue, it does not stretch/scale.Nisse
E
1

It's probably easiest to turn your drawable image into a nine-patch.

The problem you're running into is that a layer-list doesn't have an intrinsic idea of it's size. The bounds are set when it is placed inside of a container. The xml attributes are set at compile-time so it's difficult to get dynamic values inside of the xml drawable.

If you can use an ImageView, then you can set your drawable in the src attribute and use padding, margins and scaleType to control the position an scaling of the drawable.

Emir answered 27/10, 2016 at 1:5 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.