Search code examples
androidbitmapscreenshotdrawingcache

Android - getDrawingCache - black screen


I've read pretty much every post on this topic, but none of them seem to help.

I'm trying to capture a screen shot of the current screen. For this I'm using getDrawingCache. Here's my code:

mRootView.get().setDrawingCacheEnabled(true);
mRootView.get().buildDrawingCache();
Bitmap screenShot = Bitmap.createBitmap(mRootView.get().getDrawingCache());
mRootView.get().setDrawingCacheEnabled(false);

The resulting bitmap is always black.

mRootView is a weak-reference to the drawer layout, which is my root view.

Here's what I've tried:

  1. Adding a measure and layout call (although this shouldn't be needed since this code runs when a button is pressed, so the view should already be layed out).
  2. Setting the layer type to LAYER_TYPE_NONE before calling setDrawingCacheEnabled(true)
  3. Using a different view as the root view (for example, a ViewPager inside the DrawerLayout).

Nothing seems to work and I've run out of ideas.


Solution

  • You can draw your view to canvas-

    pass your main layout reference to this method-

     Bitmap file = save(layout);
    
     Bitmap save(View v)
       {
        Bitmap b = Bitmap.createBitmap(v.getWidth(), v.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas c = new Canvas(b);
        v.draw(c);
        return b;
       }