How to make view.getDrawingCache() preserving transparency

5

If I have a view with a transparent background and I do bitmap = view.getDrawingCache();, that bitmap is unfortunately no more transparent. A black background is set in background.

I have even tried

view.setDrawingCacheBackgroundColor(Color.TRANSPARENT);

without success.

Actually this method allows to set the background color without any alpha support, Color.TRANSPARENT which is 0x00000000 is actually black if you don't care about the alpha part... If I use Color.RED, the background is indeed very red.

Any idea to make this work? Is this a limitation of current Android API? Can I use draw() instead? but it's less performant that this view.getDrawingCache() I suppose (no cache)?

Thanks

android
asked on Stack Overflow Nov 27, 2015 by gre

3 Answers

0

Draw caching is somewhat of a relic of pre-HW-accelerated Android, so some stuff might be a bit confusing/not as well documented.

Transparency should work just fine as long as you leave out View#setDrawingCacheBackgroundColor(int) as this might cause the cache to drop down to 16 bit color space (see View#mDrawingCacheBackgroundColor).

This code

view.setDrawingCacheEnabled(true);
// wait for first layout
...
Bitmap b = view.getDrawingCache();

should give you an ARGB_8888 bitmap with transparent background. (You can also this in the Android Studio debugger by settings a breakpoint after the get call and 'View Bitmap' on the variable.

answered on Stack Overflow Dec 6, 2015 by user2424998
0

Try this code after setting the layout background color transparent in XML file

            layout.setDrawingCacheEnabled(true);
            Bitmap bmp = layout.getDrawingCache();
            File mFile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM), "smiley1.png");
            FileOutputStream outStream;
            outStream = new FileOutputStream(mFile);
            bmp.compress(Bitmap.CompressFormat.PNG, 100, outStream);
answered on Stack Overflow Sep 27, 2016 by Jits
0

I also get image with black background by calling getDrawingCache() method. Actually, the image has transparent background. Mistake is saving the image in jpeg format, so the gallery app shows transparent pixels in black color.

If you put it as an overlay, it'll work perfectly. There is no issue here.

answered on Stack Overflow Jun 29, 2018 by Minh Nguyen

User contributions licensed under CC BY-SA 3.0