Search code examples
androidimageviewshadowandroid-vectordrawable

Android | JAVA | How to add a shadow to vector?


I have a svg vector file. How can I add colored shadow to it. I did research on google and stackoverflow but, looks like It's not working in my case.

SVG XML

<vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:width="50dp"
    android:height="50dp"
    android:viewportWidth="35"
    android:viewportHeight="35">
  <path
      android:pathData="M18.5,18.5m-12.5,0a12.5,12.5 0,1 1,25 0a12.5,12.5 0,1 1,-25 0"
      android:fillColor="@color/green"/>
</vector>

code inside activity_main.xml

<ImageView
        android:id="@+id/green"
        android:layout_width="20dp"
        android:layout_height="20dp"
        android:src="@drawable/ic_green_light" />

I can't find a simple or even a working way to add shadow to it.

I want to add a shadow like this.. Reference image

Note : Elevation on ImageView is not working.


Solution

  • I'm not sure if the shadow works for vectors. It's probably complex to calculate all shadows that are being cast. Instead, you should create a background in the shape of your shadow:

    drawable/background.xml

    <?xml version="1.0" encoding="utf-8"?>
    <layer-list xmlns:android="http://schemas.android.com/apk/res/android">
        <item>
            <shape android:shape="oval">
                <solid android:color="@color/green" />
            </shape>
        </item>
    </layer-list>
    

    1) Elevation

    When using elevation, Android will render the shadow automatically. android:elevation="16dp on your ImageView should do the trick.

    <ImageView
        android:id="@+id/green"
        android:layout_width="20dp"
        android:layout_height="20dp"
        android:elevation="16dp"
        android:background="@drawable/background"
        android:src="@drawable/ic_green_light" />
    

    NOTE:

    The higher the elevation, the bigger and more blurred the shadow will be.

    Using a lower elevation, will result in a smaller but more crip shadow.

    For controlling the color, you can use these on API28+:

    android:outlineAmbientShadowColor="#ff0000" // api 28+ only
    android:outlineSpotShadowColor="#ff0000" // api 28+ only
    

    2) Shadow

    Another option, is to use:

    android:shadowColor="@color/almost_black"
    android:shadowDx="1.5f"
    android:shadowDy="1.5f"
    android:shadowRadius="12f"
    

    for a bit more control. But that probably requires a TextView.

    3) Change the Vector

    If all this fails, you should consider creating the shadow yourself as part of the Vector