Android實現截圖方式
本文介紹了Android 實現截圖方式整理,分享給大家。希望對大家有幫助
可能的需求:
- 截自己的屏
- 截所有的屏
- 帶導航欄截圖
- 不帶導航欄截圖
- 截圖並編輯選取一部分
- 自動擷取某個空間或者佈局
- 擷取長圖
- 在後臺去截圖
1.只擷取自己應用內部介面
1.1 擷取除了導航欄之外的螢幕
?12345678910111213141516171819 | View dView = getWindow().getDecorView(); dView.setDrawingCacheEnabled( true ); dView.buildDrawingCache(); Bitmap bitmap = Bitmap.createBitmap(dView.getDrawingCache()); if (bitmap != null ) { try { // 獲取內建SD卡路徑 String sdCardPath = Environment.getExternalStorageDirectory().getPath(); // 圖片檔案路徑 String filePath = sdCardPath + File.separator + "screenshot.png" ; File file = new File(filePath); FileOutputStream os = new FileOutputStream(file); bitmap.compress(Bitmap.CompressFormat.PNG, 100 , os); os.flush(); os.close(); DebugLog.d( "a7888" , "儲存完成" ); } catch (Exception e) { } } |
1.2 擷取某個控制元件或者區域
兩種方案:
跟上面差不多,只不過view不適用根view,而是使用某個某個控制元件。
1234 | View dView = title; dView.setDrawingCacheEnabled( true ); dView.buildDrawingCache(); Bitmap bitmap = Bitmap.createBitmap(dView.getDrawingCache()); |
手動draw
12345 | View dView = titleTv; Bitmap bitmap = Bitmap.createBitmap(dView.getWidth(), dView.getHeight(), Bitmap.Config.ARGB_8888); //使用Canvas,呼叫自定義view控制元件的onDraw方法,繪製圖片 Canvas canvas = new Canvas(bitmap); dView.draw(canvas); |
1.3 擷取帶導航欄的整個螢幕
這一小節會將一些理論上可以,但是實踐會特別複雜,不太推薦使用。可以學習瞭解。
adb 命令
這裡指的不是連線電腦進行adb操控,而是在App內部實現adb命令的操控
在APK中呼叫“adb shell screencap -pfilepath” 命令
該命令讀取系統的framebuffer,需要獲得系統許可權:
(1). 在AndroidManifest.xml檔案中新增
?1 | < uses-permissionandroid:name = "android.permission.READ_FRAME_BUFFER" /> |
(2). 修改APK為系統許可權,將APK放到原始碼中編譯, 修改Android.mk
?12345678 | LOCAL_CERTIFICATE := platform publicvoid takeScreenShot(){ String mSavedPath = Environment.getExternalStorageDirectory()+File. separator + "screenshot.png" ; try { Runtime. getRuntime().exec("screencap -p " + mSavedPath); } catch (Exception e) {
|