1. Preface
Android often encounters a situation where the view is converted to bitmap, such as taking screenshots of the entire screen view and generating images; Coverflow need to convert a page-by-page view to bitmap for complex graphical effects (shadows, reflections, etc.) , for example, some dynamic real-time view for easy observation and recording of data, the need to temporarily generate static bitmap.
2. Implementation methods
1) Here is a conversion method that I often use
int bitmapheight) { Bitmap Bitmap = bitmap.createbitmap (bitmapwidth, Bitmapheight, Bitmap.Config.ARGB_ 8888); View.draw (newreturn bitmap;}
Or use the following method:
Static Bitmap convertviewtobitmap (view view) { view.builddrawingcache (); Bitmap Bitmap = View.getdrawingcache (); return bitmap;}
In general, this method works normally. Sometimes, however, there is a problem with generating bitmap (bitmap full black). The main reason is that the value of Drawingcache is greater than the value given by the system. We can take a look at some of the code in the Builddrawingcache () method:
if (width <= 0 | | height <= 0 | | (Width * Height * (opaque &&!translucentwindow 2:4) > viewconfiguration.get (mcontext). Getscaledmaximum Drawingcachesize ())) { destroydrawingcache ()); return; }
In the above code, width and height are the widths and heights of the view drawing for the cache, so (width * height * (opaque &&!translucentwindow 2:4) calculates the current 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, a problem occurs when the bitmap is generated, and the bitmap obtained is null.
So you can fix the problem by simply modifying the desired cache value. So we introduced the second method:
2) The perfect solution
Public Static Bitmap convertviewtobitmap (view view) { view.measure (measurespec.makemeasurespec (0), measurespec.unspecified), Measurespec.makemeasurespec (0, measurespec.unspecified)); View.layout (0, 0, View.getmeasuredwidth (), View.getmeasuredheight ()); View.builddrawingcache (); =return bitmap;}
View calculates the length width using the "getmeasuredwidth ()" and "Getmeasuredheight ()" methods. At this point, the bitmap can be obtained correctly.
Solutions for view conversion to bitmap and Getdrawingcache=null in Android