天天看點

Android浏覽器多視窗webview界面截屏心得

做Android浏覽器多視窗的時候,需要使用到浏覽器的webview快照,目前有三種方法,都嘗試過,對第二種方法做了一點改進,整理說一下他們各自的優勢:

方法一:使用該方法截取webview可視部分的截圖,如使用目前方法,會截取的是最開始加載的界面,當你的界面重新整理後,并不會截取新的界面,而是使用老的界面,是以效果不太好;

private Bitmap captureWebViewVisibleSize(WebView webView){ 

   Bitmap bmp = webView.getDrawingCache(); 

   return bmp;    

}

方法二:截取整個webview的界面,包含未顯示的部分;這部分會截取整個webview的大小,由于我模拟的是ipad的模式,是以webview就會很長,而浏覽器又是記憶體大戶,故,當遇到截屏的webivew太長的時候,截取出來的bitmap太大,遇到配置低的裝置,總是出現oom,後來,對這個方法進行了改造,隻是截取顯示的内容,見下面方法三;

    private Bitmap captureWebView(WebView webView){

        Picture snapShot = webView.capturePicture();

        Bitmap bmp = Bitmap.createBitmap(snapShot.getWidth(),snapShot.getHeight(), Bitmap.Config.ARGB_8888);

        Canvas canvas = new Canvas(bmp);

        snapShot.draw(canvas);

        return bmp;

    }

方法三:對方法二的改造,通過擷取pictrue的寬,算取截屏的高,進而截取隻是顯示出來的部分,我使用的這個方法:

    private Bitmap captureWebView(WebView webView){

        Picture snapShot = webView.capturePicture();

Bitmap bmp = null;

        int width = picture.getWidth();

        int height = (int) (width * 9 / 16);//預設16:9的裝置比例,算出截屏的高

       if (width > 0 && height > 0)

        {

        bmp = Bitmap.createBitmap(width ,height , Bitmap.Config.ARGB_8888);

        Canvas canvas = new Canvas(bmp);

        snapShot.draw(canvas);

}

        return bmp;

    }

方法四:方法四就是Android的截屏操作了,沒有使用的原因是,我的浏覽器界面在webview上還有控件,使用該方法會把多餘的非webview的部分截取出來,故沒有使用該方法:

    private Bitmap captureScreen(Activity context){

      View cv = context.getWindow().getDecorView();

      Bitmap bmp = Bitmap.createBitmap(cv.getWidth(), cv.getHeight(),Config.ARGB_8888);

      Canvas canvas = new Canvas(bmp);

      cv.draw(canvas);

      return bmp;

      }