對當前Activity進行截屏的封裝代碼

ne3g 9年前發布 | 1K 次閱讀 Java Android

    public class ScreenShot {

    // 獲取指定Activity的截屏,保存到png文件  
    private static Bitmap takeScreenShot(Activity activity) {  

        // View是你需要截圖的View  
        View view = activity.getWindow().getDecorView();  
        view.setDrawingCacheEnabled(true);  
        view.buildDrawingCache();  
        Bitmap bitmap = view.getDrawingCache();  

        // 獲取狀態欄高度  
        Rect frame = new Rect();  
        activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);  
        int statusBarHeight = frame.top;  
        System.out.println(statusBarHeight);  

        // 獲取屏幕長和高  
        int width = activity.getWindowManager().getDefaultDisplay().getWidth();  
        int height = activity.getWindowManager().getDefaultDisplay().getHeight();  

        // 去掉標題欄  
        Bitmap b = Bitmap.createBitmap(bitmap, 0, statusBarHeight, width, height - statusBarHeight);  
        view.destroyDrawingCache();  
        return b;  
    }  

    // 保存到sdcard  
    private static void savePic(Bitmap b, String strFileName) {  
        FileOutputStream fos = null;  
        try {  
            fos = new FileOutputStream(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();  
        }  
    }  

    public static void shoot(Activity activity) {  
        ScreenShot.savePic(ScreenShot.takeScreenShot(activity), "sdcard/apic/image" + System.currentTimeMillis() + ".png");  
    }  
}  </pre> 


用法:

    ScreenShot.shoot(MainActivity.this);  

 本文由用戶 ne3g 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!