views:

444

answers:

1

I have done some extensive searching for code examples on this but cannot find anything.

In particular, I am looking to add a shadow to a png drawable I am using in an ImageView. This png drawable is a rounded rect with transparent corners.

Can somebody please provide a code example of how to add a decent drop shadow to a view either in code or XML?

+1  A: 

You could use a combination of Bitmap.extractAlpha and a BlurMaskFilter to manually create a drop shadow for any image you need to display, but that would only work if your image is only loaded/displayed once in a while, since the process is expensive.

Pseudo-code (might even compile!):

BlurMaskFilter blurFilter = new BlurMaskFilter(5, BlurMaskFilter.Blur.OUTER);
Paint shadowPaint = new Paint();
shadowPaint.setMaskFilter(blurFilter);

int[] offsetXY = new int[2];
Bitmap shadowImage = originalBitmap.extractAlpha(shadowPaint, offsetXY);

/* Might need to convert shadowImage from 8-bit to ARGB here, can't remember. */

Canvas c = new Canvas(shadowBitmap);
c.drawBitmap(originalBitmap, offsetXY[0], offsetXY[1], null);

Then put shadowImage into your ImageView. If this image never changes but is display a lot, you could create it and cache it in onCreate to bypass the expensive image processing.

Even if that doesn't work as is, it should be enough to get you going in the right direction.

Josh
It sort of worked… Once I changed the offsetXY[[0] and [1] in the drawBitmap to be negative of those values it lined up correctly. However, the original bitmap is drawing as a solid black image. http://cl.ly/77e6b7839c1ffc94c1e0 How to fix?
coneybeare
Not sure without seeing code. Try checking the bitdepths of the source and destination bitmaps. The problem might be that you're drawing a 32-bit image (the original) onto an 8-bit image (the extracted shadowImage). If that's the case, do something like Bitmap shadowImage32 = shadowImage.copy(ARGB_8888, true) up where I have the convert comment, and draw onto that guy instead of the 8-bit shadowImage.
Josh