Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Drawing a View manually onto a Canvas does not preserve transparency

When I draw a view, that contains transparent areas, due to its background image, these transparent areas turn black when the view is drawn to a canvas:

View v = getView();
v.measure(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
v.layout(0, 0, infoWindow.getMeasuredWidth(), infoWindow.getMeasuredWidth());
Bitmap b = Bitmap.createBitmap(v.getMeasuredWidth(), v.getMeasuredHeight(), Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(b);
//c.drawColor(Color.YELLOW); // yellow color does not show up
v.draw(c);

As the yellow background from the code snippet does not show up in the Bitmap, I conclude that v.draw(c) does not paint using transparency. If I draw a Drawable onto the canvas instead, its transparent areas are drawn correctly.

As the view is inflated from a layout file, I can observe that the same layout is rendered correctly by Android when being used within an action. So how can I draw a View onto a canvas while maintaining transparent areas?

like image 889
Lars Blumberg Avatar asked Dec 28 '25 14:12

Lars Blumberg


1 Answers

Call v.setDrawingCacheEnabled(true) and v.getDrawingCache(). The second one will give you a Bitmap which you can draw.

like image 84
Michał Z. Avatar answered Dec 31 '25 07:12

Michał Z.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!