在項目中有這樣的需求,須要把activity的試圖轉成圖片保存起來。java
步驟:android
(1)經過view.getDrawingCache()建立Bitmap對象。ui
(2)建立相應要保存圖片文件code
(3)bitmap.compress()把Bitmap對象保存到圖片文件中orm
public void screenShot(View view, String fileName) throws Exception { view.setDrawingCacheEnabled(true); view.buildDrawingCache(); //上面2行必須加入,若是不加如view.getDrawingCache()返回null Bitmap bitmap = view.getDrawingCache(); FileOutputStream fos = null; try { //判斷sd卡是否存在 boolean sdCardExist = Environment.getExternalStorageState() .equals(android.os.Environment.MEDIA_MOUNTED); if(sdCardExist){ //獲取sdcard的根目錄 String sdPath = Environment.getExternalStorageDirectory().getPath(); //建立程序本身建立的文件夾 File tempFile= new File(sdPath+File.separator +fileName); if(!tempFile.exists()){ tempFile.mkdirs(); } //建立圖片文件 File file = new File(sdPath + File.separator+fileName+File.separator+ "screen" + ".png"); if(!file.exists()){ file.createNewFile(); } image.setImageBitmap(bitmap); fos = new FileOutputStream(file); if (fos != null) { bitmap.compress(Bitmap.CompressFormat.PNG, 90, fos); fos.close(); } } } catch (Exception e) { Log.e(TAG, "cause for "+e.getMessage()); } }