Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Drop Shadow on View

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?

like image 930
coneybeare Avatar asked Aug 25 '10 15:08

coneybeare


People also ask

How do I add shadows to Kotlin?

Kotlin Android – TextView Shadow Effect To get shadow for TextView in Android, set android:elevation attribute, with required amount of elevation from the base level, for the TextView widget in layout XML file. For elevation to be effective, we should set background for the TextView.

How do you shadow text on android?

You can give -/+ values, where -Dx draws a shadow on the left of text and +Dx on the right. android:shadowDy specifies the Y-axis offset of shadow. -Dy specifies a shadow above the text and +Dy specifies below the text.

What are android shadows?

Shadows are drawn by the parent of the elevated view, and thus subject to standard view clipping, clipped by the parent by default. Elevation is also useful to create animations where widgets temporarily rise above the view plane when performing some action.


1 Answers

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(shadowImage); 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.

like image 165
Josh Avatar answered Sep 19 '22 15:09

Josh