首先通过下面的函数获取Bitmap格式的屏幕截图:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
public Bitmap myShot(Activity activity) {
        // 获取windows中最顶层的view
        View view = activity.getWindow().getDecorView();
        view.buildDrawingCache();
 
        // 获取状态栏高度
        Rect rect = new Rect();
        view.getWindowVisibleDisplayFrame(rect);
        int statusBarHeights = rect.top;
        Display display = activity.getWindowManager().getDefaultDisplay();
 
        // 获取屏幕宽和高
        int widths = display.getWidth();
        int heights = display.getHeight();
 
        // 允许当前窗口保存缓存信息
        view.setDrawingCacheEnabled(true);
 
        // 去掉状态栏
        Bitmap bmp = Bitmap.createBitmap(view.getDrawingCache(), 0,
                statusBarHeights, widths, heights - statusBarHeights);
 
        // 销毁缓存信息
        view.destroyDrawingCache();
 
        return bmp;
    }

 

得到bitmap格式的图片后,可以把它保存到sd卡中,也可以用下面的方式直接显示到ImageView上:

1
2
3
4
5
6
// 将bitmap转换成drawable
BitmapDrawable bd=new BitmapDrawable(myShot());
 
imageView.setBackgroundDrawable(bd);  
 
imageView.setImageBitmap(myShot());

如果想写入sd中保存,可以使用下面的方法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
private void saveToSD(Bitmap bmp, String dirName,String fileName) throws IOException {
        // 判断sd卡是否存在
        if (Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
            File dir = new File(dirName);
            // 判断文件夹是否存在,不存在则创建
            if(!dir.exists()){
                dir.mkdir();
            }
             
            File file = new File(dirName + fileName);
            // 判断文件是否存在,不存在则创建
            if (!file.exists()) {
                file.createNewFile();
            }
      
            FileOutputStream fos = null;
            try {
                fos = new FileOutputStream(file);
                if (fos != null) {
                    // 第一参数是图片格式,第二个是图片质量,第三个是输出流
                    bmp.compress(Bitmap.CompressFormat.PNG, 100, fos);
                    // 用完关闭
                    fos.flush();
                    fos.close();
                }
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

dirName是输出的文件夹名称,filaName是输出的文件名,两者共同组成输出的路径,如“ /mnt/sdcard/pictures/shot.png”。还要注意在AndroidManifest中注册写入权限:

1
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />