On the code:
public class Mainactivity extends Activity {ImageView imgview; @Overrideprotected void OnCreate (Bundle Savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (r.layout.activity_main); ImgView = ( ImageView) Findviewbyid (R.id.imageview); imgview.setdrawingcacheenabled (true);//This is the important code:)// Without it the view would have a dimension of 0,0 and the bitmap would be null imgview.measure (Measurespec.makemeas Urespec (0, measurespec.unspecified), Measurespec.makemeasurespec (0, measurespec.unspecified)); ImgView.layout (0 , 0, Imgview.getmeasuredwidth (), Imgview.getmeasuredheight ()); Bitmap Bitmap = Bitmap.createbitmap (Imgview.getdrawingcache ()); imgview.setdrawingcacheenabled (false); String strpath = "/testsaveview/" +uuid.randomuuid (). toString () + ". png"; if (Environment.getexternalstoragestate (). Equals (environment.media_mounted)) {File sdcarddir=environment.getexternalstoragedirectory (); FileOutputStream fos = null; try{File File = new file (sdcarddir, strpath); if (!file.getparentfile (). exists ()) {File.getparentfile (). mkdirs (); fos = new FileOutputStream (file); When you specify a compressed format as PNG, the saved picture shows normal bitmap.compress (compressformat.jpeg, +, FOS); When the specified compression format is JPEG, the picture background is black//bitmap.compress (compressformat.jpeg, FOS); Fos.flush (); }catch (Exception e) {e.printstacktrace ();} finally{try {fos.close ();} catch (IOException e) {e.printstacktrace ();}}}}
Activity_main.xml:
<linearlayout xmlns:android= "http://schemas.android.com/apk/res/android" android:layout_width= "Match_ Parent " android:layout_height=" match_parent " android:orientation=" vertical "> <imageview Android:id= "@+id/imageview" android:layout_width= "100DP" android:layout_height= "100DP" android: Scaletype= "Centerinside" android:src= "@drawable/ic_launcher"/></linearlayout>
There are two questions to be aware of:
First, the call Getdrawingcache () before the measurement, otherwise the resulting bitmap is null, this I in the OnCreate (), OnStart (), Onresume () methods have been tested.
Second, when the call Bitmap.compress (Compressformat.jpeg, A, FOS); Save as a picture when you find the picture background is black, such as:
At this point only need to change to use PNG to save it, Bitmap.compress (Compressformat.png,,, FOS), such as:
The "Android" method to save the view as a picture and to solve the problem of black background when the image is saved