我有一个网页视图,我需要向下滚动才能查看所有内容。现在,我想将整个 webview 捕获为位图。 我找了很多次。人们建议我使用该功能
capturePicture()
。但是,此功能已
已弃用。那么,我还可以使用哪些其他方法来实现我的目标? 谢谢大家。
米哈伊尔·纳加诺夫
:https://stackoverflow.com/a/30084485/703225
@Override
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
WebView.enableSlowWholeDocumentDraw();
}
...
setContentView(layout);
...
...
}
然后:
/**
* WevView screenshot
*
* @param webView
* @return
*/
public static Bitmap screenshot(WebView webView, float scale11) {
try {
float scale = webView.getScale();
int height = (int) (webView.getContentHeight() * scale + 0.5);
Bitmap bitmap = Bitmap.createBitmap(webView.getWidth(), height, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
webView.draw(canvas);
return bitmap;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
如果你不使用 webView.getScale(),也:
public static Bitmap screenshot2(WebView webView) {
webView.measure(MeasureSpec.makeMeasureSpec(
MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED),
MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
webView.layout(0, 0, webView.getMeasuredWidth(), webView.getMeasuredHeight());
webView.setDrawingCacheEnabled(true);
webView.buildDrawingCache();
Bitmap bitmap = Bitmap.createBitmap(webView.getMeasuredWidth(),
webView.getMeasuredHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
Paint paint = new Paint();
int iHeight = bitmap.getHeight();
canvas.drawBitmap(bitmap, 0, iHeight, paint);
webView.draw(canvas);
return bitmap;
}
webView.draw()
使用软件渲染绘制元素,因此无法绘制
<canvas>
以及可能其他一些元素,这些元素有时对网站(例如游戏)至关重要。从 Android 8.0 开始,可以使用硬件加速创建离屏 Surface 并绘制视图(包括 webView),这也可以绘制 <canvas>
元素。
这是执行此操作的代码:final View view = webView;
final Bitmap bitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.ARGB_8888);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
final SurfaceTexture surfaceTexture = new SurfaceTexture(false);
surfaceTexture.setDefaultBufferSize(view.getWidth(), view.getHeight());
final Surface surface = new Surface(surfaceTexture);
final Canvas hwCanvas = surface.lockHardwareCanvas();
view.draw(hwCanvas);
surface.unlockCanvasAndPost(hwCanvas);
PixelCopy.request(surface, bitmap, new PixelCopy.OnPixelCopyFinishedListener() {
@Override
public void onPixelCopyFinished(int copyResult) {
if (copyResult != PixelCopy.SUCCESS) {
// failed to pixelcopy, fallback to software draw
view.draw(new Canvas(bitmap));
}
surface.release();
surfaceTexture.release();
// use your bitmap here
onBitmapDone.run(bitmap);
}
}, new Handler());
} else {
view.draw(new Canvas(bitmap));
onBitmapDone.run(bitmap);
}