Android中截取当前屏幕的功能

来源:互联网 发布:可变数据印刷软件价格 编辑:程序博客网 时间:2024/04/30 15:36
该篇文章是说明在Android手机或平板电脑中如何实现截取当前屏幕的功能,并把截取的屏幕保存到SDCard中的某个目录文件夹下面。实现的代码如下:
[html] view plaincopyprint?
  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.        
  12.     Bitmap Bmp = Bitmap.createBitmap( w, h, Config.ARGB_8888 );       
  13.        
  14.     //2.获取屏幕   
  15.     View decorview = this.getWindow().getDecorView();    
  16.     decorview.setDrawingCacheEnabled(true);    
  17.     Bmp = decorview.getDrawingCache();    
  18.      
  19.     String SavePath = getSDCardPath()+"/AndyDemo/ScreenImage"; 
  20.    
  21.     //3.保存Bitmap    
  22.     try {   
  23.         File path = new File(SavePath);   
  24.         //文件   
  25.         String filepath =SavePath + "/Screen_1.png";   
  26.         File file = new File(filepath);   
  27.         if(!path.exists()){   
  28.             path.mkdirs();   
  29.         }   
  30.         if (!file.exists()) {   
  31.             file.createNewFile();   
  32.         }   
  33.            
  34.         FileOutputStream fos = null;   
  35.         fos = new FileOutputStream(file);   
  36.         if (null != fos) {   
  37.             Bmp.compress(Bitmap.CompressFormat.PNG, 90, fos);   
  38.             fos.flush();   
  39.             fos.close();     
  40.                
  41.             Toast.makeText(mContext, "截屏文件已保存至SDCard/AndyDemo/ScreenImage/下", Toast.LENGTH_LONG).show();   
  42.         }   
  43.    
  44.     } catch (Exception e) {   
  45.         e.printStackTrace();   
  46.     }   
  47. }   
  48.  
  49.    /** 
  50.     * 获取SDCard的目录路径功能 
  51.     * @return 
  52.     */ 
  53. private String getSDCardPath(){ 
  54.     File sdcardDir = null
  55.     //判断SDCard是否存在 
  56.     boolean sdcardExist = Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED); 
  57.     if(sdcardExist){ 
  58.         sdcardDir = Environment.getExternalStorageDirectory(); 
  59.     } 
  60.     return sdcardDir.toString(); 

由于要对SDCard进行操作,所以别忘记了在manifest.xml文件中赋以对SDCard的读写权限:

[html] view plaincopyprint?
  1. <uses-permissionandroid:name="android.permission.WRITE_EXTERNAL_STORAGE"/