簡體   English   中英

如何在android 5.0中將webview捕獲到位圖?

[英]How to capture the webview to bitmap in android 5.0?

在這里,我對webview有一個快速的問題。

我的要求是捕獲Webview並將文件保存在sdcard中,以保存為我在以下代碼中使用的文件。

下面的代碼用於從webview生成位圖

Webview到位圖:

webview.measure(MeasureSpec.makeMeasureSpec(
               MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED),
               MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
       webview.layout(0, 0, webview.getMeasuredWidth(),
               webview.getMeasuredHeight());
       webview.setDrawingCacheEnabled(true);
       webview.buildDrawingCache();
      bitmap = Bitmap.createBitmap(webview.getMeasuredWidth(),
               webview.getMeasuredHeight(), Bitmap.Config.ARGB_8888);

       Canvas bigcanvas = new Canvas(bitmap);
       Paint paint = new Paint();
       int iHeight = bitmap.getHeight();
       bigcanvas.drawBitmap(bitmap, 0, iHeight, paint);
       webview.draw(bigcanvas);

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

   webview.setDrawingCacheEnabled(false);

下面的代碼用於將文件保存在內存中

要另存為文件:

 File myDir = new File(Environment.getExternalStorageDirectory(), "Sample");
    if (myDir.exists()) 
    {
    } 
    else 
    {
        myDir.mkdir();
    }
    String fname = "sample" + ".png";
    file1 = new File(myDir, fname);

   if(bitmap!=null)
   { 

    try 
    {
        FileOutputStream out = new FileOutputStream(file1);
        bitmap.compress(Bitmap.CompressFormat.PNG, 10, out);
        out.flush();
        out.close();
    } 
    catch (Exception e) 
    {
        e.printStackTrace();
    }}

但是這里的webview可以很好地加載但不能完全在android 5.0(lollipop)中捕獲,如下圖所示

在此處輸入圖片說明

我該如何解決這個問題? 請給我建議或一些代碼片段。

提前致謝..

U可以在畫布上繪制視圖,如下所示:

        Bitmap mBitmap;
        Layout webViewContainer
        mBitmap =  Bitmap.createBitmap(webViewContainer.getWidth(), webViewContainer.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(mBitmap);
        webViewContainer.draw(canvas);

創建任何WebView之前,您需要調用WebView.enableSlowWholeDocumentDraw()。 也就是說,如果布局中有任何WebView,請確保先調用此方法,然后在如下所示的onCreate()中調用setContentView()。

if (Build.VERSION.SDK_INT >= 21) {
        webview.enableSlowWholeDocumentDraw ();
}

對我來說很好

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM