我想在没有UI交互的情况下在后台转换Image中的HTML。我发现使用webview我们可以做到这一点。但Android已弃用webview.capturePicture();方法,我们也需要UI交互。
答案 0 :(得分:0)
首先使用正确的布局参数在代码中实例化新的WebView
:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
WebView.enableSlowWholeDocumentDraw();
}
WebView webView = new WebView(context);
FrameLayout frameLayout = new FrameLayout(context);
frameLayout.setLayoutParams(new FrameLayout.LayoutParams(512, 100));
webView.setLayoutParams(new FrameLayout.LayoutParams(512, FrameLayout.LayoutParams.WRAP_CONTENT));
frameLayout.addView(webView);
webView.setDrawingCacheEnabled(true);
然后设置WebViewClient
以便在webview完成加载时收听:
webView.setWebViewClient(new WebViewClient() {
public boolean shouldOverrideUrlLoading(final WebView view, String url) {
return false;
}
@Override
public void onPageFinished(final WebView view, String url) {
Log.i("HTML", "page finished loading " + url);
view.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
view.buildDrawingCache(true);
Bitmap b = Bitmap.createBitmap(view.getDrawingCache());
// bitmap is ready
} ) ;
然后将您的html加载到WebView
:
webView.loadDataWithBaseURL(null, YOUR_HTML_STRING, "text/html", "UTF-8", null);
重要提示:在所有步骤中,确保网页浏览量的宽度和高度不为零;