1

I'm trying to save a screenshot of my current Activity, but not the whole view, just part of it. In my case: My activity

At the attached image, i want to save a bitmap constructed from views B,C & D.

B is a linear layout, C is a pure bitmap, and D is a relative layout.

To my understanding, one way to go is creating a canvas, add all 'elements' into it and finally have the custom bitmap desired.

I'm having trouble with the following code:

iViewBHeight= viewB.getHeight();
// Prepare empty bitmap as output
Bitmap result = Bitmap.createBitmap(bitmapC.getWidth(),bitmapC.getHeight() +     iViewBHeight, Config.ARGB_8888);
// Flush source image into canvas
Canvas canvas = new Canvas(result);
// Draw bitmap C to canvas 'under' view B
canvas.drawBitmap(bitmapC, 0, iViewBHeight, null);
// Draw view B to canvas
viewB.setDrawingCacheEnabled(true);
viewB.buildDrawingCache(true);
canvas.drawBitmap(Bitmap.createBitmap(viewB.getDrawingCache()), 0, 0, null);
viewB.setDrawingCacheEnabled(false);

// Desired bitmap is at 'result'

The result is that bitmap C is drawn Ok, but view B is too large and extends the bitmap. I didn't try adding view D..

Can anyone help me? Maybe there are better ways achieving my goal? Thanks!

Alon
  • 48
  • 6

1 Answers1

2

I think the easiest way to accomplish that is to grab a screenshot of the Activity's entire content, then crop off the A View. The Canvas#drawBitmap(Bitmap bmp, Rect src, Rect dest, Paint pnt) overload does this easily. The Rect src describes section of the source Bitmap you're copying, while dest is the section of the destination Bitmap that the source will be drawn in. (NB: the Rects don't have to be the same size.)

I believe the following method should do what you want, if I'm following you correctly.

private Bitmap capture()
{
    View actContent = findViewById(android.R.id.content);

    Bitmap result = Bitmap.createBitmap(actContent.getWidth(),
                                        actContent.getHeight() - viewA.getHeight(),
                                        Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(result);

    actContent.setDrawingCacheEnabled(true);
    Rect src = new Rect(0, viewA.getHeight(), actContent.getWidth(), actContent.getHeight());
    Rect dest = new Rect(0, 0, result.getWidth(), result.getHeight());
    canvas.drawBitmap(actContent.getDrawingCache(), src, dest, null);
    actContent.setDrawingCacheEnabled(false);

    return result;
}
Mike M.
  • 38,532
  • 8
  • 99
  • 95
  • 1
    Amazing, Its exactly what i was looking for. I didn't know it is possible to do that! Thank you Mike! – Alon Oct 11 '15 at 07:52