Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extending Android View class to add a dropshadow

I want to extend LinearLayout so that when my layout is drawn a drop shadow is added underneath it. I've played around overriding the onDraw method but I'm a bit lost. Any help with this or even library suggestions would be greatly appreciated!

Here's an example of the drop shadow view I am trying to achieve. I don't believe I can use a nine patch here because I need the contents of the view to be within the white box. This would mean I would need to know the distance between the border and the end of the PNG. However I believe different screen densities mean that this distance will always be the same PX but not the same DP.

So to be clear I need a way to extend the View class so that a drop shadow is drawn under it when it is added to a layout. No XML or 9Patch solutions please.

enter image description here

Thanks

Jack

like image 217
JackMahoney Avatar asked Feb 18 '13 06:02

JackMahoney


People also ask

How do add shadow above a view in Android?

There is no such attribute in Android, to show a shadow. But possible ways to do it are: Add a plain LinearLayout with grey color, over which add your actual layout, with margin at the bottom and right equal to 1 or 2 dp.

How to give elevation to shape in Android?

To set the default (resting) elevation of a view, use the android:elevation attribute in the XML layout. To set the elevation of a view in the code of an activity, use the View. setElevation() method. To set the translation of a view, use the View.

What is Android elevation?

Elevation (Android) Elevation is the relative depth, or distance, between two surfaces along the z-axis. Specifications: Elevation is measured in the same units as the x and y axes, typically in density-independent pixels (dp).


1 Answers

I agree with the comments on your question: programmatic dropshadow effect is a bad choice, and you could achieve the same effect with a simple 9patch (or a set of them) like stated here.

BTW I was too curious, and I ended with hacking a solution after work.

The code presented is a test, and should be intended as a simple proof-of-concept (so please don't downvote). Some of the operations shown are quite expensive, and may seriously impact on the performances (There are many examples around, look here, here to get an idea). It should be a last resort solution only for a component shown once-in-a-while.

public class BalloonView extends TextView {

  protected NinePatchDrawable bg;
  protected Paint paint;
  protected Rect padding = new Rect();
  protected Bitmap bmp;

  public BalloonView(Context context) {
    super(context);
init();
  }

  public BalloonView(Context context, AttributeSet attrs) {
    super(context, attrs);
init();
  }

  public BalloonView(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
    init();
  }

  @SuppressLint("NewApi")
  protected void init() {
    // decode the 9patch drawable
    bg = (NinePatchDrawable) getResources().getDrawable(R.drawable.balloon);

    // get paddings from the 9patch and apply them to the View
    bg.getPadding(padding);
    setPadding(padding.left, padding.top, padding.right, padding.bottom);

    // prepare the Paint to use below
    paint = new Paint();
    paint.setAntiAlias(true);
    paint.setColor(Color.rgb(255,255,255));
    paint.setStyle(Style.FILL);

    // this check is needed in order to get this code
    // working if target SDK>=11
    if( Build.VERSION.SDK_INT >= 11 )
      setLayerType(View.LAYER_TYPE_SOFTWARE, paint);

    // set the shadowLayer
    paint.setShadowLayer(
      padding.left * .2f, // radius
      0f, // blurX
      padding.left * .1f, // blurY
      Color.argb(128, 0, 0, 0) // shadow color
    );
  }

  @Override
  protected void onDraw(Canvas canvas) {
    int w = getMeasuredWidth();
    int h = getMeasuredHeight();

    // set 9patch bounds according to view measurement
    // NOTE: if not set, the drawable will not be drawn
    bg.setBounds(0, 0, w, h);

    // this code looks expensive: let's do once
    if( bmp == null ) {

      // it seems like shadowLayer doesn't take into account
      // alpha channel in ARGB_8888 sources...
      bmp = Bitmap.createBitmap(w, h, Config.ARGB_8888);

      // draw the given 9patch on the brand new bitmap
      Canvas tmp = new Canvas(bmp);
      bg.draw(tmp);

      // extract only the alpha channel
      bmp = bmp.extractAlpha();
    }

    // this "alpha mask" has the same shape of the starting 9patch,
    // but filled in white and **with the dropshadow**!!!!
    canvas.drawBitmap(bmp, 0, 0, paint);

    // let's paint the 9patch over...
    bg.draw(canvas);

    super.onDraw(canvas);
  }
}

First of all in order to get programmatic drop shadow you have to deal with Paint.setShadowLayer(...) like stated here. Basically you should define a shadow layer for the Paint object used to draw on the Canvas of your custom view. Unfortunately you cannot use a Paint object to draw a NinePatchDrawable, so you need to convert it into a Bitmap (1st hack). Furthermore it seems like shadow layers can't work properly with ARGB_8888 images, so the only way I found in order to get a proper shadow has been to draw the alpha mask of the given NinePatchDrawable (2nd hack) just below itself.

Here's a couple of sshots (tested on Android 2.3.3@mdpi and 4.2.2@xhdpi) enter image description hereenter image description here

Edit: just to be thorough, I attached the 9patch used in the test (placed in res/drawable/mdpi) enter image description here

like image 69
a.bertucci Avatar answered Oct 10 '22 04:10

a.bertucci