Android截屏

    xiaoxiao2022-07-04  167

    public class ViewShot {    

    // 获取指定Activity的截屏,保存到png文件

        static String newFilePath;    

    private static File sFileParent;  

      private static Bitmap takeScreenShot(Activity activity) {    

        // View是你需要截图的View      

      View view = activity.getWindow().getDecorView();    

        view.setDrawingCacheEnabled(true);        

    view.buildDrawingCache();        

    Bitmap b1 = view.getDrawingCache();      

      // 获取状态栏高度        

    Rect frame = new Rect();        

    activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);        

    int statusBarHeight = frame.top;         // 获取屏幕长和高      

      int width = activity.getWindowManager().getDefaultDisplay().getWidth();    

        int height = activity.getWindowManager().getDefaultDisplay().getHeight();  

          //截图的窗框位置        

    Bitmap b = Bitmap.createBitmap(b1, (int) (width / 10), (int) (height / 4), (int) (width * 0.8), (int) (height * 0.6)         );         view.destroyDrawingCache();         return b;     }  

      // 保存到sdcard    

    private static void savePic(Bitmap b, String strFileName, Activity activity) {    

        FileOutputStream fos = null;        

    //判断是否存在该文件夹和文件,如果没有新建    

        File file = new File(strFileName);      

      try {             //获取父目录          

      sFileParent = file.getParentFile();        

        //判断是否存在        

        if (!sFileParent.exists()) {

    //   

     创建父目录文件              

      sFileParent.mkdirs();             }            

    file.createNewFile();          

      fos = new FileOutputStream(new File(strFileName));          

      if (null != fos) {              

      b.compress(Bitmap.CompressFormat.PNG, 90, fos);      

              fos.flush();          

          fos.close();             }        

    } catch (FileNotFoundException e) {             e.printStackTrace();         } catch (IOException e) {             e.printStackTrace();         }        

    UIUtils.showToastSafe("截图保存在" + sFileParent.toString());    

    }    

    //用于获取当前最新的截图    

    public static String getPath() {        

    return newFilePath;     }    

    // 截屏方法    

        // 截屏方法     public static void shoot(Activity a) {         Date date = new Date();         SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");         String fileName = df.format(date) + ".png";         String sdCardPath = Environment.getExternalStorageDirectory().getPath();         // String filePath = sdCardPath + File.separator + "456" + File.separator + "qrcode" + File.separator + fileName;

            String filePath = Environment.getExternalStorageDirectory()                 + File.separator + Environment.DIRECTORY_DCIM                 + File.separator + "哈哈哈" + File.separator + fileName;

            newFilePath = filePath;         ViewShot.savePic(ViewShot.takeScreenShot(a), filePath, a);     }

    }

    最新回复(0)