Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving View bitmap with getDrawingCache gives a black image

Everything I tried with setDrawingCacheEnabled and getDrawingCache was not working. The system was making an image but it just looked black.

Other people on SO seemed to be having a similar problem but the answers seemed either too complicated or irrelevant to my situation. Here are some of the ones I looked at:

  • Save view like bitmap, I only get black screen
  • Screenshot shows black
  • getDrawingCache always returns the same Bitmap
  • Convert view to bitmap on Android
  • bitmap is not saving properly only black image
  • Custom view converting to bitmap returning black image

And here is my code:

    view.setDrawingCacheEnabled(true);
    Bitmap bitmap = view.getDrawingCache();
    try {
        FileOutputStream stream = new FileOutputStream(getApplicationContext().getCacheDir() + "/image.jpg");
        bitmap.compress(CompressFormat.JPEG, 80, stream);
        stream.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    view.setDrawingCacheEnabled(false);

I'm sharing my answer below in case anyone else makes the same mistake I did.

like image 666
Suragch Avatar asked Aug 19 '14 03:08

Suragch


2 Answers

My problem was that my view was a TextView. The text on the TextView was black (naturally) and in the app the background looked white. However, I later recalled reading that a view's background is by default transparent so that whatever color is below shows through.

So I added android:background="@color/white" to the layout xml for the view and it worked. When I had been viewing the image before I had been looking at black text over a black background.

See the answer by @BraisGabin for an alternate way that does not require overdrawing the UI.

like image 111
Suragch Avatar answered Sep 23 '22 14:09

Suragch


I just found a good option:

final boolean cachePreviousState = view.isDrawingCacheEnabled();
final int backgroundPreviousColor = view.getDrawingCacheBackgroundColor();
view.setDrawingCacheEnabled(true);
view.setDrawingCacheBackgroundColor(0xfffafafa);
final Bitmap bitmap = view.getDrawingCache();
view.setDrawingCacheBackgroundColor(backgroundPreviousColor);
bitmap.compress(Bitmap.CompressFormat.JPEG, 80, stream);
view.setDrawingCacheEnabled(cachePreviousState);

Where 0xfffafafa is the desired background color.

like image 38
Brais Gabin Avatar answered Sep 22 '22 14:09

Brais Gabin