First get the bitmap format screen by using the following function:
| 123456789101112131415161718192021222324252627 |
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; } |
After you get the bitmap format picture, you can save it to the SD card, or you can display it directly on the ImageView in the following way:
| 123456 |
// 将bitmap转换成drawableBitmapDrawable bd=newBitmapDrawable(myShot()); imageView.setBackgroundDrawable(bd); imageView.setImageBitmap(myShot()); |
If you want to write to the SD save, you can use the following method:
| 1234567891011121314151617181920212223242526272829303132333435 |
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 is the name of the output folder, and Filaname is the file name of the output, which together form the output path, such as "/mnt/sdcard/pictures/shot.png". Also be aware of registering write permissions in Androidmanifest:
| 1 |
<uses-permissionandroid:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
|
Android Development Gets the current Activity screen (reprint)