2012-11-21 66 views
2

我想從webiview中捕獲圖片,它在我嘗試從網頁加載loadUrl時起作用,但是當我嘗試在資源中加載本地html文件或在String中加載html時它crashs,出現以下錯誤:從webview中捕獲圖片加載本地html

java.lang.IllegalArgumentException: width and height must be > 0 
    at android.graphics.Bitmap.createBitmap(Bitmap.java:638) 
    at android.graphics.Bitmap.createBitmap(Bitmap.java:620) 

我的代碼是:

//Create the webview 

WebView w = new WebView(this); 

w.setWebViewClient(new WebViewClient() { 
    public void onPageFinished(WebView view, String url) { 
     //get the picture from webview 
     Picture picture = view.capturePicture(); 

     Bitmap b = Bitmap.createBitmap(picture.getWidth(), 
         picture.getHeight(), Bitmap.Config.ARGB_8888); 

     Canvas c = new Canvas(b); 

     picture.draw(c); 

     FileOutputStream fos = null; 

     try { 

     String path = Environment.getExternalStorageDirectory().toString(); 
     File dir = new File(path, "/Movel/media/img/"); 
     if (!dir.isDirectory()) { 
      dir.mkdirs(); 
     } 
     String arquivo = "darf_"+ System.currentTimeMillis() + ".jpg"; 
     File file = new File(dir, arquivo); 

     fos = new FileOutputStream(file); 
     String imagePath = file.getAbsolutePath(); 
     //scan the image so show up in album 
     MediaScannerConnection.scanFile(MainActivity.this, new String[] { imagePath }, 
         null, new MediaScannerConnection.OnScanCompletedListener() { 
          public void onScanCompleted(String path, Uri uri) { 

          } 
          }); 

     if (fos != null) { 
      b.compress(Bitmap.CompressFormat.JPEG, 90, fos); 

      fos.close(); 
     } 

     } catch (Exception e) { 
     e.printStackTrace(); 
     } 
    } 
    }); 

setContentView(w); 

String html = "<html><head><meta http-equiv='Content-Type' content='text/html; charset=ISO-8859-1'> " + 
    "<title>Demo Html</title> </head> <body> <H1>Testing One Two Three</H1> </body></html>"; 

//load from assets 
//w.loadDataWithBaseURL("file:///android_asset/", Strings.converterParaElementosHTMLEspeciais(html), "text/html", "iso-8859-1", null); 
//w.loadUrl("file:///android_asset/darf.html"); 
//w.loadUrl("https://www.google.com.br"); 
w.loadData(html, "text/html", "iso-8859-1"); 

回答

2

這個錯誤,因爲你的WebView寬度和高度爲0,所以你必須LayoutWebView,然後再嘗試這種代碼:

myWebView.setWebChromeClient(new WebChromeClient() { 
     @Override 
     public void onProgressChanged(WebView view, int newProgress) { 
      super.onProgressChanged(view, newProgress); 
      if (newProgress == 100) { 
       view.post(new Runnable() { 

        @Override 
        public void run() { 
         // take the snapshot here 


        } 
       }); 

      } 
     } 

    }); 
+0

謝謝!有效! – JosafaSSJ

+0

然後接受答案 –

+0

我所做的唯一更改是放在onProgressChanged方法的webview參數中。 public void onProgressChanged(最終的WebView視圖,int newProgress){ – JosafaSSJ

相關問題