[Android] how to save a view as an image and solve the problem of changing the background of the saved image to black,
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 will have a dimension of 0, 0 and the bitmap will be null img View. measure (MeasureSpec. makeMeasureSpec (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. getExter NalStorageState (). 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 the specified compression format is PNG, the saved image shows normal bitmap. compress (CompressFormat. JPEG, 100, fos); // when the specified compression format is JPEG, the background of the saved image is black // bitmap. compress (CompressFormat. JPEG, 100, 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>
Pay attention to two issues:
1. measurement is required before calling getDrawingCache (). Otherwise, the bitmap obtained is null. I have tried this in the OnCreate (), OnStart (), and OnResume () methods.
2. When bitmap. compress (CompressFormat. JPEG, 100, fos) is called and saved as an image, the background of the image is black, for example:
In this case, you only need to save it with png, bitmap. compress (CompressFormat. PNG, 100, fos);, for example: