android 对当前Activity截屏

来源:互联网 发布:mac chm阅读器 编辑:程序博客网 时间:2024/05/21 21:42

From:http://blog.csdn.net/kazeik/article/details/8681498

[java] view plaincopy
  1. import java.io.FileNotFoundException;  
  2. import java.io.FileOutputStream;  
  3. import java.io.IOException;  
  4.   
  5. import android.app.Activity;  
  6. import android.graphics.Bitmap;  
  7. import android.graphics.Rect;  
  8. import android.util.Log;  
  9. import android.view.View;  
  10.   
  11. public class ScreenShot {  
  12.     // 获取指定Activity的截屏,保存到png文件  
  13.     private static Bitmap takeScreenShot(Activity activity) {  
  14.         // View是你需要截图的View  
  15.         View view = activity.getWindow().getDecorView();  
  16.         view.setDrawingCacheEnabled(true);  
  17.         view.buildDrawingCache();  
  18.         Bitmap b1 = view.getDrawingCache();  
  19.   
  20.         // 获取状态栏高度  
  21.         Rect frame = new Rect();  
  22.         activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);  
  23.         int statusBarHeight = frame.top;  
  24.         Log.i("TAG""" + statusBarHeight);  
  25.   
  26.         // 获取屏幕长和高  
  27.         int width = activity.getWindowManager().getDefaultDisplay().getWidth();  
  28.         int height = activity.getWindowManager().getDefaultDisplay()  
  29.                 .getHeight();  
  30.         // 去掉标题栏  
  31.         // Bitmap b = Bitmap.createBitmap(b1, 0, 25, 320, 455);  
  32.         Bitmap b = Bitmap.createBitmap(b1, 0, statusBarHeight, width, height  
  33.                 - statusBarHeight);  
  34.         view.destroyDrawingCache();  
  35.         return b;  
  36.     }  
  37.   
  38.     // 保存到sdcard  
  39.     private static void savePic(Bitmap b, String strFileName) {  
  40.         FileOutputStream fos = null;  
  41.         try {  
  42.             fos = new FileOutputStream(strFileName);  
  43.             if (null != fos) {  
  44.                 b.compress(Bitmap.CompressFormat.PNG, 90, fos);  
  45.                 fos.flush();  
  46.                 fos.close();  
  47.             }  
  48.         } catch (FileNotFoundException e) {  
  49.             e.printStackTrace();  
  50.         } catch (IOException e) {  
  51.             e.printStackTrace();  
  52.         }  
  53.     }  
  54.   
  55.     // 程序入口  
  56.     public static void shoot(Activity a) {  
  57.         ScreenShot.savePic(ScreenShot.takeScreenShot(a), "sdcard/xx.png");  
  58.     }  
  59. }  
  60.   
  61.    
  62.   
  63.    
  64.   
  65. 需要注意的是,shoot方法只能在view已经被加载后方可调用。  
  66.   
  67. 或者在    @Override  
  68.     public void onWindowFocusChanged(boolean hasFocus) {  
  69.         // TODO Auto-generated method stub  
  70.         super.onWindowFocusChanged(hasFocus);  
  71.         ScreenShot.shoot(this);  
  72.     }中调用  

1 0
原创粉丝点击