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:
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With