最近項目有個 webView 里面截圖的需求瓤狐。記錄一下瞬铸。
// 獲取根視圖
View dView = context.getWindow().getDecorView();
// 啟用繪圖緩存
dView.setDrawingCacheEnabled(true);
// 調用緩存
dView.buildDrawingCache();
Bitmap bitmap = Bitmap.createBitmap(dView.getDrawingCache());
// 獲取內置SD卡路徑
String sdCardPath = Environment.getExternalStorageDirectory().getPath();
// 圖片文件路徑
Calendar calendar = Calendar.getInstance();
String creatTime = calendar.get(Calendar.YEAR) + "-" +
calendar.get(Calendar.MONTH) + "-"
+ calendar.get(Calendar.DAY_OF_MONTH) + " "
+ calendar.get(Calendar.HOUR_OF_DAY) + ":"
+ calendar.get(Calendar.MINUTE);
String filePath = sdCardPath + File.separator + "shot_" + creatTime + ".png";
if (bitmap != null) {
try {
File file = new File(filePath);
FileOutputStream os = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, os);
os.flush();
os.close();
XjjLogManagerUtil.d(TAG, "存儲完成");
} catch (Exception e) {
e.printStackTrace();
}
}
通過上述代碼截圖后,發(fā)現(xiàn)一個問題础锐。webView 里面截圖的一些圖片是沒有顯示的嗓节。在網上查了一下,需要在 webView 的 xml 布局文件里面加上一行屬性設置
android:layerType="software"
<WebView
android:id="@+id/webView"
android:layerType="software"
android:layout_width="match_parent"
android:layout_height="match_parent" />
這樣子就能夠正常截圖了皆警。webView 中的圖片也能正常在截圖中顯示出來了拦宣。
然而又發(fā)現(xiàn)了一個問題,就是每次在同一個 webView 中截圖信姓,保存的圖片永遠是第一張圖片鸵隧,初步猜測是因為緩存問題,于是換了種截圖方式
//獲取webview縮放率
float scale = webView.getScale();
//得到縮放后webview內容的高度
int webViewHeight = (int) (webView.getContentHeight()*scale);
Bitmap bitmap = Bitmap.createBitmap(webView.getWidth(),webViewHeight, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
//繪制
webView.draw(canvas);
發(fā)現(xiàn)從 webView 獲取的截圖意推,有時候會有一大段空白豆瘫。所以又改成了從 decorView 中獲取當前屏幕。
View decorView = getContext().getWindow().getDecorView();
Bitmap bitmap = Bitmap.createBitmap(decorView.getWidth(), decorView.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
//繪制
decorView.draw(canvas);
這樣子截圖功能最終就做好了菊值。缺點就是把標題欄也給帶進去了外驱。但能保證截圖的是 webView 當前顯示的全部內容。 所以最終代碼是
View decorView = getContext().getWindow().getDecorView();
Bitmap bitmap = Bitmap.createBitmap(decorView.getWidth(), decorView.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
//繪制
decorView.draw(canvas);
// 獲取內置SD卡路徑
String sdCardPath = Environment.getExternalStorageDirectory().getPath();
// 圖片文件路徑
Calendar calendar = Calendar.getInstance();
String creatTime = calendar.get(Calendar.YEAR) + "-" +
calendar.get(Calendar.MONTH) + "-"
+ calendar.get(Calendar.DAY_OF_MONTH) + " "
+ calendar.get(Calendar.HOUR_OF_DAY) + ":"
+ calendar.get(Calendar.MINUTE) + ":"
+ calendar.get(Calendar.SECOND);
String filePath = sdCardPath + File.separator + "shot_" + creatTime + ".png";
if (bitmap != null) {
try {
File file = new File(filePath);
if (file.exists()) {
file.delete();
}
FileOutputStream os = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, os);
os.flush();
os.close();
XjjLogManagerUtil.d(TAG, "存儲完成");
} catch (Exception e) {
e.printStackTrace();
}
}