主题 : 【代码】android -- 截屏-view.getDrawingCache() 复制链接 | 浏览器收藏 | 打印
欢迎加入清源的android开发交流群:314230976,加群时请验证:arm,谢谢!
级别: 侠客
UID: 94332
精华: 0
发帖: 72
金钱: 370 两
威望: 74 点
综合积分: 144 分
注册时间: 2013-07-14
最后登录: 2013-09-25
楼主  发表于: 2013-08-21 14:44

 【代码】android -- 截屏-view.getDrawingCache()

在项目中有这样的需求,需要把activity的试图转成图片保存起来。

步骤:

(1)通过view.getDrawingCache()创建Bitmap对象。

(2)创建相应要保存图片文件

(3)bitmap.compress()把Bitmap对象保存到图片文件中

复制代码
  1. view sourceprint?
  2. 01
  3. public void screenShot(View view, String fileName) throws Exception {
  4. 02
  5. view.setDrawingCacheEnabled(true);
  6. 03
  7. view.buildDrawingCache();
  8. 04
  9. //上面2行必须加入,如果不加如view.getDrawingCache()返回null
  10. 05
  11. Bitmap bitmap = view.getDrawingCache();
  12. 06
  13. FileOutputStream fos = null;
  14. 07
  15. try {
  16. 08
  17. //判断sd卡是否存在
  18. 09
  19. boolean sdCardExist = Environment.getExternalStorageState()
  20. 10
  21. .equals(android.os.Environment.MEDIA_MOUNTED);
  22. 11
  23. if(sdCardExist){
  24. 12
  25. //获取sdcard的根目录
  26. 13
  27. String sdPath = Environment.getExternalStorageDirectory().getPath();
  28. 14
  29. 15
  30. //创建程序自己创建的文件夹
  31. 16
  32. File tempFile= new File(sdPath+File.separator +fileName);
  33. 17
  34. if(!tempFile.exists()){
  35. 18
  36. tempFile.mkdirs();
  37. 19
  38. }
  39. 20
  40. //创建图片文件
  41. 21
  42. File file = new File(sdPath + File.separator+fileName+File.separator+ "screen" + ".png");
  43. 22
  44. if(!file.exists()){
  45. 23
  46. file.createNewFile();
  47. 24
  48. }
  49. 25
  50. 26
  51. image.setImageBitmap(bitmap);
  52. 27
  53. fos = new FileOutputStream(file);
  54. 28
  55. if (fos != null) {
  56. 29
  57. 30
  58. bitmap.compress(Bitmap.CompressFormat.PNG, 90, fos);
  59. 31
  60. fos.close();
  61. 32
  62. }
  63. 33
  64. }
  65. 34
  66. 35
  67. 36
  68. } catch (Exception e) {
  69. 37
  70. Log.e(TAG, "cause for "+e.getMessage());
  71. 38
  72. }
  73. 39
  74. }
欢迎加入android开发交流群,群号是:314230976