Saturday, December 3, 2011

How create a Bitmap image of the WebView in Android in case of many page navigations?

The easiest way to create a bitmap of a web view loaded is do webView.capturePicture()
But this gives the content of the whole page, which is not only visible part in the screen. Also it doesn't care whether page is scaled or not and scrolled to a position. If we want to create a bitmap image for the view which is only visible in the screen, we have to do webView.getDrawingCache() and to make this work you have to call webView.setDrawingCacheEnabled(true) in earlier.

This gives the content of the web page, which is cached for the reuse, in the form of the bitmap.
But some times we may have to navigate between pages. If we do webView.getDrawingCache() after some page navigation we may not know which cached copy will be returned as bitmap. Some times we may get bitmap of some old page.

And here is the simple way I found to overcome it. Perhaps you may know it already. Well it is the very simple way than how it looks like. Disable the drawing caching or don't call  webView.setDrawingCacheEnabled(true) and cache the content manually when it is required as it is explained in following way.

Before you call webView.getDrawingCache()  you have to do  webView.buildDrawingCache() ** . Then create the bitmap of the cache content. One trad off of this is, since you are manually caching the content, you have clear by yourself by calling webView.destroyDrawingCache(). Otherwise the app memory will be keep on filling up. Also I experienced a strange issue the if you do webView.destroyDrawingCache() in very next line of webView.getDrawingCache() you will get blank bitmap. So you have to destroy cache content either when you next come to create a bitmap or onDestroy() of the activity or something like that. You should decide it on your requirement bases.