歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Android中截取當前屏幕的功能

Android中截取當前屏幕的功能

日期:2017/3/1 10:30:06   编辑:Linux編程

該篇文章是說明在Android手機或平板電腦中如何實現截取當前屏幕的功能,並把截取的屏幕保存到SDCard中的某個目錄文件夾下面。實現的代碼如下:

  1. /**
  2. * 獲取和保存當前屏幕的截圖
  3. */
  4. private void GetandSaveCurrentImage()
  5. {
  6. //1.構建Bitmap
  7. WindowManager windowManager = getWindowManager();
  8. Display display = windowManager.getDefaultDisplay();
  9. int w = display.getWidth();
  10. int h = display.getHeight();
  11. Bitmap Bmp = Bitmap.createBitmap( w, h, Config.ARGB_8888 );
  12. //2.獲取屏幕
  13. View decorview = this.getWindow().getDecorView();
  14. decorview.setDrawingCacheEnabled(true);
  15. Bmp = decorview.getDrawingCache();
  16. String SavePath = getSDCardPath()+"/AndyDemo/ScreenImage";
  17. //3.保存Bitmap
  18. try {
  19. File path = new File(SavePath);
  20. //文件
  21. String filepath = SavePath + "/Screen_1.png";
  22. File file = new File(filepath);
  23. if(!path.exists()){
  24. path.mkdirs();
  25. }
  26. if (!file.exists()) {
  27. file.createNewFile();
  28. }
  29. FileOutputStream fos = null;
  30. fos = new FileOutputStream(file);
  31. if (null != fos) {
  32. Bmp.compress(Bitmap.CompressFormat.PNG, 90, fos);
  33. fos.flush();
  34. fos.close();
  35. Toast.makeText(mContext, "截屏文件已保存至SDCard/AndyDemo/ScreenImage/下", Toast.LENGTH_LONG).show();
  36. }
  37. } catch (Exception e) {
  38. e.printStackTrace();
  39. }
  40. }
  41. /**
  42. * 獲取SDCard的目錄路徑功能
  43. * @return
  44. */
  45. private String getSDCardPath(){
  46. File sdcardDir = null;
  47. //判斷SDCard是否存在
  48. boolean sdcardExist = Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
  49. if(sdcardExist){
  50. sdcardDir = Environment.getExternalStorageDirectory();
  51. }
  52. return sdcardDir.toString();
  53. }

由於要對SDCard進行操作,所以別忘記了在manifest.xml文件中賦以對SDCard的讀寫權限:

  1. <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Copyright © Linux教程網 All Rights Reserved