2015-12-28 182 views
1

我試圖加載一些html代碼的webview,然後捕獲它並轉換成位圖。但是,在我設置的ImageView中可以看到的所有內容都是空白的方塊。將webview轉換爲位圖

webViewToPrint.loadDataWithBaseURL("", dataStringHtml , "text/html", "UTF-8", ""); 
webViewToPrint.setWebViewClient(new WebViewClient() { 
     @Override 
     public void onPageFinished(WebView view, String url) { 
       super.onPageFinished(view, url); 

       Bitmap b = Bitmap.createBitmap(view.getHeight(), view.getWidth(), Config.ARGB_8888); 
       Canvas canvas = new Canvas(b); 
       view.draw(canvas); 
       imageView.setImageBitmap(b);  
     }}); 
+1

我可以幫助你:http://stackoverflow.com/questions/30409630/how-to-capture-the-webview-to-bitmap-in-android-5-0 – santoXme

回答

1
webViewToPrint.setWebViewClient(new WebViewClient() 
    { 
      public void onPageFinished(WebView view, String url) 
      { 
        Picture picture = view.capturePicture(); 
        Bitmap b = Bitmap.createBitmap(picture.getWidth(), 
        picture.getHeight(), Bitmap.Config.ARGB_8888); 
        Canvas c = new Canvas(b); 
        picture.draw(c); 
        imageView.setImageBitmap(b); }} 
+0

imageView是空的..現在它甚至不顯示像它用來測試的 – BVtp

+0

什麼版本的白色矩形? (Build.VERSION.SDK_INT> = 21)webview.enableSlowWholeDocumentDraw(); () }確保你在onCreate()中調用setContentView()之前調用這個方法() –

+0

我的設備是API 19,所以我不能使用enableSlowWholeDocumentDraw() – BVtp

0

使用下面的代碼:

webViewToPrint.setDrawingCacheEnabled(true); 

在onPageFinished()

Bitmap bitmap = Bitmap.createBitmap(view.getDrawingCache()); 
imageView.setImageBitmap(bitmap); 
1

謝謝你們的幫助。解決方案的難點是在onPageFinished內添加另一個線程(postDelayed),並延遲一段時間(在我的情況下500工作正常)。