Drop shadow for Floating Action Button

2.1k views Asked by At

enter image description here

I'm creating my own floating action button. For this I'm using a RippleDrawable (created by me) and a ShadowDrawable (also created by me). The problem I'm facing is that my ShadowDrawbale does not cast perfect shadow for the respective button. The code for my ShadowDrawable is as follows:

public class ShadowDrawable extends Drawable {

private Context context;
private float floatMaximumRadius = 0;
private int intCenterX = 0, intCenterY = 0, intShadowAlpha,intShadowColor;
private Paint paintShadow;

public ShadowDrawable(Context context) {
    this.context = context;
    paintShadow = new Paint(Paint.ANTI_ALIAS_FLAG);
    paintShadow.setStyle(Paint.Style.FILL);
}

@Override
public void draw(Canvas canvas) {
    paintShadow.setShadowLayer(dpToPx(4f), dpToPx(1f), dpToPx(3f), intShadowColor);
    paintShadow.setAlpha(intShadowAlpha);
    paintShadow.setColor(intShadowColor);
    canvas.drawCircle(intCenterX, intCenterY, floatMaximumRadius, paintShadow);
}

@Override
public int getOpacity() {
    return 0;
}

@Override
protected void onBoundsChange(Rect rectBounds) {
    super.onBoundsChange(rectBounds);
    intCenterX = rectBounds.centerX();
    intCenterY = rectBounds.centerY();
    floatMaximumRadius = (Math.min(rectBounds.width(), rectBounds.height()) / 2) - 4;
}

@Override
public void setAlpha(int alpha) {
    setShadowAlpha(alpha);
}

@Override
public void setColorFilter(ColorFilter cf) {

}

public void setShadowAlpha(int intShadowAlpha) {
    this.intShadowAlpha = intShadowAlpha;
    invalidateSelf();
}

public void setShadowColor(int intShadowColor) {
    this.intShadowColor = intShadowColor;
    invalidateSelf();
}

private int dpToPx(float dp) {
    final float scale = context.getResources().getDisplayMetrics().density;
    return Math.round(dp * scale);
}

}

Tell me how to make the shadow clear and proper just like the one of floating action button given in support library.

1

There are 1 answers

2
Edwin On BEST ANSWER

You can check out this fab library here here at GitHub. The library allows you to set ripple effect colour on the fab.

<com.melnykov.fab.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|right"
        android:layout_margin="16dp"
        android:src="@drawable/ic_action_content_new"
        fab:fab_colorNormal="@color/primary"
        fab:fab_colorPressed="@color/primary_pressed"
        fab:fab_colorRipple="@color/ripple" />