美文网首页
Andorid截图

Andorid截图

作者: 傲娇的狗蛋 | 来源:发表于2018-07-18 17:24 被阅读0次

    前言

    最近项目里有用到截图,总结一些用法。

    截图

        /**
         * 截取除了导航栏之外的整个屏幕
         */
        private Bitmap screenShotWholeScreen() {
            View dView = getWindow().getDecorView();
            dView.setDrawingCacheEnabled(true);
            dView.buildDrawingCache();
            Bitmap bitmap = Bitmap.createBitmap(dView.getDrawingCache());
            return bitmap;
    
        }
    

    获取View在屏幕可见区域的截图

       /**
         * 获取View在屏幕可见区域的截图
         */
        private Bitmap screenShotView(View view) {
            //开启缓存功能
            view.setDrawingCacheEnabled(true);
            //创建缓存
            view.buildDrawingCache();
            //获取缓存Bitmap
            Bitmap bitmap = Bitmap.createBitmap(view.getDrawingCache());
            return bitmap;
        }
    

    webview截图

    webview很多时候都是滚动显示html。所及截的图也是长图。这里分为两种情况处理。

    5.0以下:

        /**
         * 对WebView进行截屏,虽然使用过期方法,但在当前Android版本中测试可行
         * @param webView
         * @return
         */
        private static Bitmap captureWebViewKitKat(WebView webView) {
                Picture picture = webView.capturePicture();
                int width = picture.getWidth();
                int height = picture.getHeight();
                if (width > 0 && height > 0) {
                    Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
                    Canvas canvas = new Canvas(bitmap);
                    picture.draw(canvas);
                    return bitmap;
                }
                return null;
            }
        }
    

    5.0以上:

    5.0以上的版本对webview有优化,webveiw只绘制显示部分。如果截长图需要在初始化页面之前先关闭优化。

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                WebView.enableSlowWholeDocumentDraw();
            }
            setContentView(R.layout.activity_test);
    

    使用以下方法截图:

        private void captureWebViewLollipop(WebView webView) {
            float scale = webView.getScale();
            int width = webView.getWidth();
            int height = (int) (webView.getContentHeight() * scale + 0.5);
            Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
            Canvas canvas = new Canvas(bitmap);
            webView.draw(canvas);
            return bitmap;
        }
    

    代码传送门

    相关资料:

    WebView截长图解决方案

    Android长截屏-- ScrollView,ListView及RecyclerView截屏

    开源库scrollscreenshot

    相关文章

      网友评论

          本文标题:Andorid截图

          本文链接:https://www.haomeiwen.com/subject/dzcapftx.html