现在好多APP的分享多了个“长图文分享”,自己在开发中也遇到了这个需求,正好作个记录吧
1. Android5.0以下版本
通过google提供的Api就可以轻易实现需求:
private static Bitmap captureWebViewKitKat(WebView webView) {
Picture picture = webView.capturePicture();
int width = picture.getWidth();
int height = picture.getHeight();
if (width > 0 && height > 0) {
Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_888);
Canvas canvas = new Canvas(bitmap);
picture.draw(canvas);
return bitmap;
}
return null;
}
}
2. Android5.0以上版本
依然使用上面的方法就会遇到一个问题——只截取到可见部分的内容,其他的全部为空白。原来,在Android5.0及以上版本,Android对WebView进行了优化,为了减少内存使用和提高性能,使用WebView加载网页时只绘制显示部分。Google也提供了关闭这个优化的方法,请看:
//在webview实例化前调用
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
android.webkit.WebView.enableSlowWholeDocumentDraw();
}
//示例代码,没做异步处理
private void captureWebView(WebView webView) {
float scale = webView.getScale();
int width = webView.getWidth();
int height = (int) (webView.getContentHeight() * scale + 0.5);
Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_888);
Canvas canvas = new Canvas(bitmap);
webView.draw(canvas);
File f = new File(Environment.getExternalStorageDirectory(),"capture.jpg");
try {
if(!f.createNewFile()) {
System.out.println("File already exists");
}
} catch (IOException ex) {
}
writeBitmapToFile(bitmap,f);
}
public static boolean writeBitmapToFile(Bitmap bitmap, File path) {
boolean isCompress = false;
FileOutputStream out = null;
try {
out = new FileOutputStream(path);
if (path.getName().toLowerCase().endsWith(".jpg")) {
isCompress = bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
} else {
isCompress = bitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
}
out.flush();
out.close();
} catch (Exception e) {
} finally {
try {
if (out != null) {
out.close();
}
} catch (IOException ioe) {
// ignore
}
}
return isCompress;
}