本次需求是要实现对WebView显示所有内容的截图 网上找了一通,基本上是实现了当前显示内容的截图,并非是整个页面的截图。
最终实现效果和代码如下所示,实现了本次WebView长截图的需求。 效果如下:
代码如下,主要是使用WebView.setDrawingCacheEnabled(),WebView.buildDrawingCache(),WebView.getDrawingCache(),View.scrollBy() 实现滑动截图,再拼接合成整张图片。
1 | public class CaptureUtils { |
图片保存代码:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22private void takeCapture() {
Bitmap bitmap = webViewFragment.captureWebView(); //获取webview 长截图,内部代码是上面代码所示,调用了CaptureUtils.getWebViewBitmap();
String filePath = CachePathNew.getDCIMPath(activityInstance) + "线下支付_" + TimeUtils.getNowStringSimple() + ".jpg";
File file = new File(filePath);
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 70, fos);
ToastUtils.makeText("图片已保存到\n" + fileName);
Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
Uri uri = Uri.fromFile(file);
intent.setData(uri);
activityInstance.sendBroadcast(intent);
notification(filePath);
fos.flush();
fos.close();
} catch (Exception e) {
e.printStackTrace();
ToastUtils.makeText("保存失败");
CloseUtils.closeIO(fos);
}
}
发送notification,点击用系统图片浏览工具打开图片1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29private void notification(String filePath) {
int indexS = filePath.indexOf("DCIM");
String subFilePath;
if (-1 != indexS) {
subFilePath = filePath.substring(indexS - 1);
} else {
subFilePath = filePath;
}
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
File file = new File(filePath);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(file), "image/* ");
PendingIntent pendingIntent = PendingIntent.getActivity(activityInstance, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
Notification.Builder builder = new Notification.Builder(activityInstance);
builder.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("已保存订单截图信息")
.setContentText(subFilePath)
.setAutoCancel(true)
.setContentIntent(pendingIntent);
Notification notification;
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
notification = builder.getNotification();
} else {
notification = builder.build();
}
manager.notify((int) System.currentTimeMillis(), notification);
}
通知效果如下