在项目中有这样的需求,须要把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()); } }