开发者

Android -- Displaying background WebView as a Bitmap

I would like to load a webview in the background and only display a bitmap of the page it loads. I have a webview in my view hierarchy that has visibility set to "invisible" and an imageview that I wish to display a bitmap of the webview.

imageView = (ImageView)findViewById(R.id.imageview);
webView = (WebView)findViewById(R.id.webview);
webView.setBackgroundColor(Color.parseColor("#006330"));

webView.setDrawingCacheEnabled(true);
webView.loadDataWithBaseURL(SiteAPI.URL, html, "text/html", "i开发者_C百科so-8859-1", null);

webView.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED), 
                    MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
webView.layout(0, 0, webView.getMeasuredWidth(), webView.getMeasuredHeight());

Bitmap b = webView.getDrawingCache(); 
webView.setDrawingCacheEnabled(false);          

if(b != null) {
     Toast.makeText(getBaseContext(), "Not null", Toast.LENGTH_LONG).show();
     imageView.setImageBitmap(Bitmap.createBitmap(b));
}
else {
     Toast.makeText(getBaseContext(), "Null.", Toast.LENGTH_LONG).show();
}

The call to getDrawingCache() returns null everytime. I've tried setContentView(webView) and the page displays fine. I've made sure that isDrawingCacheEnabled() returns true, yet the bitmap is still null. Where am I going wrong?


You have two options:

  1. Use webView.capturePicture() method, but note that this will return a picture of the whole webpage, so you have to crop it to display just the part that you want.

  2. Manually draw your webView in the Canvas object you want, using webView.draw(Canvas).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜