Sapan Diwakar

Software developer

Follow me on Twitter Check out my code on GitHub View some of my designs on Dribbble Take a look at my Linked In profile

Adding shadows to views in Android using 9-patch image

This is a topic that has been discussed quite a lot in the past. But I couldn't find an easy solution that outlines the steps for creating shadows around views in Android. In this post, I will outline the process right from the beginning.

The first step is to create a png image with a shadow around it. I used photoshop to create such an image. Its really simple.

  1. Create a new image with Photoshop.
  2. Add a layer and create a black square of 4x4.
  3. Create a shadow on the layer by selecting the layer in layer explorer and clicking on a button titled fx and choosing drop shadow.
  4. Export the image as png.

If you want to skip this step, here are the images that I prepared.



The next step is to create 9-patch drawables from this image.

  1. Open draw9patch from android-sdk/tools
  2. Open the image in draw9patch
  3. Create 4 black lines on the four sides of the square like the following and then save the image as shadow.9.png.


Here is the 9patch image of the black version if you don't want to create your own.




Now you can add this shadow as the background of the views you want to add the shadow to. Add shadow.9.png to res/drawables. Here's how to add this to a linearLayout:

<LinearLayout  
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:background="@drawable/shadow"
  android:paddingBottom="5px"
  android:paddingLeft="6px"
  android:paddingRight="5px"
  android:paddingTop="5px"
>

The padding here is important and if you created your own image with photoshop, then you might need to change these values for your images. The rule is that the padding should be the number of pixels from a corner of the image to beginning of your shadow.