Search code examples
androidandroid-drawable

Vector splash screen image with a half of screen size on Android


I have a splash screen with a vector image of size 480dp and radial gradient:

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape android:shape="rectangle" >
            <!-- <solid android:color="#FF07862c"/> -->
            <gradient
                android:type="radial"
                android:startColor="#086824"
                android:endColor="#098a2f"
                android:gradientRadius="480dp"
                android:centerX="0.5"
                android:centerY="0.5"/>
        </shape>
    </item>
    <!-- <item android:drawable="@drawable/background0" android:gravity="center"/> -->
    <item android:drawable="@drawable/logo"
        android:width="480dp"
        android:height="480dp"
        android:gravity="center"/>
</layer-list>

how to make the the image size

min(screen_width, screen_height) / 2

(in pseudo-code)?

apptheme.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <style name="AppTheme" parent="@android:style/Theme.DeviceDefault.Light.NoActionBar">
        <item name="android:windowBackground">@drawable/splash</item>
    </style>
</resources>

AndroidManifest.xml:

    <activity android:name="com.myapp.MainActivity"
        android:theme="@style/AppTheme"

Solution

  • You can do this several ways by modifying layer properties of LayerDrawable as runtime. For your drawable.xml you can modify the layer at index 1 as follows. then you need to set windowBackground at runtime.

    val layerDrawable = ContextCompat.getDrawable(this,R.drawable.test) as LayerDrawable
        val size = resources.displayMetrics.widthPixels.coerceAtMost(resources.displayMetrics.heightPixels) /2
        layerDrawable.setLayerGravity(1,Gravity.CENTER)
        layerDrawable.setLayerHeight(1,size)
        layerDrawable.setLayerWidth(1,size)
        window.setBackgroundDrawable(layerDrawable)
    

    Similarly you can modify any layer if you need. first layer will be a GradientDrawable if you need to change it get the drawable for layerDrawable and cast it to GradientDrawable . then you can change its properties.