webView及ScrollView长截图

前言

之前的文章已经讲了X5内核加入到项目中的方式,现在写一下如何在该内核下使用长截图,Android自带的webView也适用改方式。

都是轮子,我直接上代码了,以下是webView的长截图

 private Bitmap captureScreenforRecord(){

        webView.measure(View.MeasureSpec.makeMeasureSpec(
                View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED),
                View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
        webView.layout(0, 0, webView.getMeasuredWidth(),
                webView.getMeasuredHeight());
        webView.setDrawingCacheEnabled(true);
        webView.buildDrawingCache();

        Bitmap bm = Bitmap.createBitmap(webView.getMeasuredWidth(),
                webView.getMeasuredHeight(), Bitmap.Config.RGB_565);

        Canvas bigcanvas = new Canvas(bm);
        Paint paint = new Paint();
        int iHeight = bm.getHeight();
        bigcanvas.drawBitmap(bm, 0, iHeight, paint);
        webView.draw(bigcanvas);
        return  bm;
    }

浏览器截图

webView及ScrollView长截图_第1张图片
image.png

点击screen按钮后跳转至pictureActivity

webView及ScrollView长截图_第2张图片
image.png

正常的webView还有一种截图的方式,

  float scale = webView.getScale();
        int webViewHeight = (int) (webView.getContentHeight()*scale);
        Bitmap bitmap = Bitmap.createBitmap(webView.getWidth(),webViewHeight, Bitmap.Config.RGB_565);
        Canvas canvas = new Canvas(bitmap);
        webView.draw(canvas);

但是在X5 内核的webView不可用,会出现屏幕外为黑屏。在Android5.0以后的webView也可能出现黑色,如下

webView及ScrollView长截图_第3张图片
image.png

需要进行一些处理:

   static {//webView长截图分享在api21以上需要处理
        if(Build.VERSION.SDK_INT >= 21){
            WebView.enableSlowWholeDocumentDraw();
        }
    }

不过在X5内核下以上方法时被屏蔽的,所以不推荐使用,可以在原生的webView中使用,内存消耗会变大。

另外附上ScrollView长截图代码

  float scale = webView.getScale();
        int webViewHeight = (int) (webView.getContentHeight()*scale);
        Bitmap bitmap = Bitmap.createBitmap(webView.getWidth(),webViewHeight, Bitmap.Config.RGB_565);
        Canvas canvas = new Canvas(bitmap);
        webView.draw(canvas);

链接附上 github
CaptureScreenWithTencentX5

你可能感兴趣的:(webView及ScrollView长截图)