【android】把view儲存為圖片的方法以及解決儲存後圖片背景變黑色的問題

來源:互聯網
上載者:User

標籤:android   圖片   

上代碼:

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          imgView.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.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); //當指定壓縮格式為PNG時儲存下來的圖片顯示正常 bitmap.compress(CompressFormat.JPEG, 100, fos);  //當指定壓縮格式為JPEG時儲存下來的圖片背景為黑色// 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>


需要注意兩個問題:

一、調用getDrawingCache()前先要測量,否則的話得到的bitmap為null,這個我在OnCreate()、OnStart()、OnResume()方法裡都實驗過。

二、當調用bitmap.compress(CompressFormat.JPEG, 100, fos);儲存為圖片時發現圖片背景為黑色,如:


這時只需要改成用png儲存就可以了,bitmap.compress(CompressFormat.PNG, 100, fos);,如:




【android】把view儲存為圖片的方法以及解決儲存後圖片背景變黑色的問題

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.