Skip to content

Instantly share code, notes, and snippets.

@vxhviet
Last active November 26, 2020 09:48
Show Gist options
  • Save vxhviet/e18f8915bc39f766de45c68090573825 to your computer and use it in GitHub Desktop.
Save vxhviet/e18f8915bc39f766de45c68090573825 to your computer and use it in GitHub Desktop.

How to Draw shadow without disabling Hardware acceleration

SOURCE

The trick is to create an additional Canvas to draw a shadow Bitmap and then cache it:

    private Context mContext;
    private Bitmap valueBackgroundBitmap = null;
    private Bitmap generateBallBitmap() {
        final int shadowSize = (int) ViewUtilKt.convertDpToPx(mContext, 8);
        final int width = (int) ViewUtilKt.convertDpToPx(mContext, 80);
        final int height = (int) ViewUtilKt.convertDpToPx(mContext, 30);

        Paint paint = new Paint();
        paint.setAntiAlias(true);
        paint.setColor(Color.WHITE);
        paint.setShadowLayer(shadowSize, 0, shadowSize, ContextCompat.getColor(mContext, R.color.shadow));

        Bitmap bitmap = Bitmap.createBitmap(width + 50, height + 50, Bitmap.Config.ARGB_8888);
        bitmap.eraseColor(Color.TRANSPARENT);
        Canvas canvas = new Canvas(bitmap);
        canvas.drawRect(0, 0, width, height, paint);

        return bitmap;
    }

and then use in the onDraw() or whichever one you want to draw:

  @Override
    public void drawValue(Canvas c, String valueText, float x, float y, int color) {
        if (null == this.valueBackgroundBitmap) {
            this.valueBackgroundBitmap = generateBallBitmap();
        }
        c.drawBitmap(valueBackgroundBitmap, x, y, null);
    }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment