Android原生WebView截图(支持缩放)

Android原生WebView截图,支持Android 5.0及以上,支持缩放

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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
/**
* 缩放图
* @param context
* @param webView
*/
public static void captureScaleWebViewLollipop(final Context context, final WebView webView) {
final float scale = webView.getScale();
final int height = (int) (webView.getContentHeight() * scale);
final int width = (int) (webView.getWidth() * scale);
if (scale > 3) {
NToasty.shortToastError(context, context.getResources().getString(R.string.webview_scale_too_large));
return;
}
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
Log.i("yezhou", "width: " + width + ", height: " + height + ", scale: " + scale);
int pH = webView.getHeight();
int pW = webView.getWidth();
final Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
Canvas canvas = new Canvas(bitmap);
int top = 0;
int left = 0;
while (top < height) {
left = 0;
while (left < width) {
canvas.save();
if (left + pW < width && top + pH < height) {
canvas.clipRect(left, top, left + pW, top + pH);
//因缩放后内容宽高大概率不是WebView宽高的整数倍,导致末端无法滑动至此位置
webView.scrollTo(left, top);
} else if (left + pW > width && top + pH < height) {
canvas.clipRect(width - pW, top, width, top + pH);
webView.scrollTo(width - pW, top);
} else if (left + pW < width && top + pH > height) {
canvas.clipRect(left, height - pH, left + pW, height);
webView.scrollTo(left, height - pH);
} else {
canvas.clipRect(width - pW, height - pH, width, height);
webView.scrollTo(width - pW, height - pH);
}
webView.draw(canvas);
canvas.restore();
left += pW;
}
top += pH;
}
saveWebViewBitmap(context, bitmap);
}
}, 100);
}

Powered by AppBlog.CN     浙ICP备14037229号

Copyright © 2012 - 2020 APP开发技术博客 All Rights Reserved.

访客数 : | 访问量 :