Search code examples
javaandroidnine-patch

Android: 9-patch splash screen won't maintain aspect ratio


I know, the subject is almost older than Android itself but I went through pretty much every single 9-patch tutorial there is and I still can't make my splash screen maintain its aspect ratio. Below is a 9-patch PNG image literally copied from tutorials as a version that's supposed to keep the logo centered without stretching no matter the aspect ratio. I've tried every possible thing and it just keeps stretching e.g. between 16:9 and 18.5:9 devices. What am I doing wrong?

My 9-patch image

My launcher theme in styles.xml:

    <style name="AppTheme.Launcher">
    <item name="android:windowBackground" >@drawable/splash</item>
        <item name="colorPrimaryDark">@android:color/black</item>
    </style>

My manifest pointing to that theme:

android:theme="@style/AppTheme.Launcher"

And my MainActivity where we switch back to regular theme on startup:

 protected void onCreate(Bundle savedInstanceState) {
        setTheme(R.style.AppTheme);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

Any help is much appreciated, thank you.


Solution

  • Instead of passing your splash drawable directly as the windowBackground, try to include it in a bitmap tag within a layer-list drawable and pass that drawable as the windowBackground.

    You can also draw a solid color underneath the bitmap in your layer-list as the background.

    background_splash.xml

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

    And then add it in your style:

    <item name="android:windowBackground">@drawable/background_splash</item>