在项目中有这样的需求,需要把activity的试图转成图片保存起来。
步骤:
(1)通过view.getDrawingCache()创建Bitmap对象。
(2)创建相应要保存图片文件
(3)bitmap.compress()把Bitmap对象保存到图片文件中
复制代码- view sourceprint?
- 01
- public void screenShot(View view, String fileName) throws Exception {
- 02
- view.setDrawingCacheEnabled(true);
- 03
- view.buildDrawingCache();
- 04
- //上面2行必须加入,如果不加如view.getDrawingCache()返回null
- 05
- Bitmap bitmap = view.getDrawingCache();
- 06
- FileOutputStream fos = null;
- 07
- try {
- 08
- //判断sd卡是否存在
- 09
- boolean sdCardExist = Environment.getExternalStorageState()
- 10
- .equals(android.os.Environment.MEDIA_MOUNTED);
- 11
- if(sdCardExist){
- 12
- //获取sdcard的根目录
- 13
- String sdPath = Environment.getExternalStorageDirectory().getPath();
- 14
- 15
- //创建程序自己创建的文件夹
- 16
- File tempFile= new File(sdPath+File.separator +fileName);
- 17
- if(!tempFile.exists()){
- 18
- tempFile.mkdirs();
- 19
- }
- 20
- //创建图片文件
- 21
- File file = new File(sdPath + File.separator+fileName+File.separator+ "screen" + ".png");
- 22
- if(!file.exists()){
- 23
- file.createNewFile();
- 24
- }
- 25
- 26
- image.setImageBitmap(bitmap);
- 27
- fos = new FileOutputStream(file);
- 28
- if (fos != null) {
- 29
- 30
- bitmap.compress(Bitmap.CompressFormat.PNG, 90, fos);
- 31
- fos.close();
- 32
- }
- 33
- }
- 34
- 35
- 36
- } catch (Exception e) {
- 37
- Log.e(TAG, "cause for "+e.getMessage());
- 38
- }
- 39
- }
|