1. Foreword
Android often encounters situations where a view is converted to bitmap, such as screenshots of the entire screen view and the creation of a picture; in Coverflow, you need to convert one page view to bitmap to achieve complex graphical effects (shadows, reflections, etc.) , such as some dynamic real-time view to facilitate the observation and recording of data, the need to temporarily generate static bitmap.
2. Implementation methods
1) The following is the author often used a conversion method
public static Bitmap Convertviewtobitmap (view view, int bitmapwidth, int bitmapheight) {
Bitmap Bitmap = bitmap.create Bitmap (Bitmapwidth, Bitmapheight, Bitmap.Config.ARGB_8888);
View.draw (New Canvas (bitmap));
return bitmap;
}
Or use the following method:
public static Bitmap Convertviewtobitmap (view view) {
view.builddrawingcache ();
Bitmap Bitmap = View.getdrawingcache ();
return bitmap;
}
In general, this method works properly. Sometimes, however, there is a problem with generating bitmap (bitmap All Black). The main reason is that the value of Drawingcache is greater than the value given by the system. We can look at a piece of code in the Builddrawingcache () method:
if (width <= 0 | | height <= 0 | | (Width * Height * (opaque &&!translucentwindow 2:4) > Viewconfiguration.get (mcontext). Getscaledmaximumdraw Ingcachesize ()) {
destroydrawingcache ());
Return
In the code above, width and height are the widths and heights of the view drawn by the cache, so (width * height * (opaque &&!translucentwindow 2:4) calculates the currently required CAC He size. Viewconfiguration.get (Mcontext). Getscaledmaximumdrawingcachesize () Gets the maximum Drawingcache value provided by the system. When the required Drawingcache > system provides the maximum Drawingcache value, the build bitmap problems occur and the bitmap obtained is null.
So you can solve the problem only if you need to modify the cache value. So we introduced the second method:
2 Perfect Solution
public static Bitmap Convertviewtobitmap (view view) {
view.measure (0, measurespec.unspecified), Measurespec.makemeasurespec (0, measurespec.unspecified));
View.layout (0, 0, view.getmeasuredwidth (), View.getmeasuredheight ());
View.builddrawingcache ();
Bitmap Bitmap = View.getdrawingcache ();
return bitmap;
}
View uses the Getmeasuredwidth () and Getmeasuredheight () methods to calculate the length of the width. At this point, bitmap can get it right.
The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.