【转】android屏幕截图

时间:2022-06-14 05:54:50
01 android屏幕截图
02  
03     import java.io.FileNotFoundException; 
04     import java.io.FileOutputStream; 
05     import java.io.IOException; 
06        
07     import android.app.Activity; 
08     import android.graphics.Bitmap; 
09     import android.graphics.Rect; 
10     import android.view.View; 
11        
12     public class ScreenShot { 
13         // 获取指定Activity的截屏,保存到png文件 
14         private static Bitmap takeScreenShot(Activity activity){ 
15             //View是你需要截图的View 
16             View view = activity.getWindow().getDecorView(); 
17             view.setDrawingCacheEnabled(true); 
18             view.buildDrawingCache(); 
19             Bitmap b1 = view.getDrawingCache(); 
20                
21             //获取状态栏高度 
22             Rect frame = new Rect();   
23             activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);   
24             int statusBarHeight = frame.top;   
25             System.out.println(statusBarHeight); 
26                
27             //获取屏幕长和高 
28             int width = activity.getWindowManager().getDefaultDisplay().getWidth();   
29             int height = activity.getWindowManager().getDefaultDisplay().getHeight();   
30             //去掉标题栏 
31             //Bitmap b = Bitmap.createBitmap(b1, 0, 25, 320, 455); 
32             Bitmap b = Bitmap.createBitmap(b1, 0, statusBarHeight, width, height - statusBarHeight); 
33             view.destroyDrawingCache(); 
34             return b; 
35         
36            
37         //保存到sdcard 
38         private static void savePic(Bitmap b,String strFileName){ 
39             FileOutputStream fos = null
40             try 
41                 fos = new FileOutputStream(strFileName); 
42                 if (null != fos) 
43                 
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     }