UI

TextureView和界面View截图整合

2017-11-07  本文已影响621人  一洼世界

业务需求:最近做TV业务,使用 TextureView 播放视频,底部有滚动字幕。这里截图需要全部截取到。如果root的话可以用指令screencap -p 去截图。这里没有Root的情况。

/**
     * 获取和保存当前屏幕的截图 返回真实路径
     * <p>
     * 这里TextureView 实现 textureview + 整个ViewGroup 截图 =叠加 Canva绘制
     */
    public String cropVideoImage(TextureView textureView, View layoutView, WindowManager windowManager) {
        if (textureView == null || layoutView == null) {
            return null;
        }

        File imgFile = new File(dirFile, UUID.randomUUID() + ".png");
        Bitmap content = textureView.getBitmap();
        layoutView.setDrawingCacheEnabled(true);
//        Bitmap layout = layoutView.getDrawingCache();
        Bitmap layout = convertViewToBitmap(layoutView);
        Bitmap screenshot = Bitmap.createBitmap(layout.getWidth(), layout.getHeight(), Bitmap.Config.ARGB_8888);

        Display defaultDisplay = windowManager.getDefaultDisplay();
        DisplayMetrics metrics = new DisplayMetrics();
        defaultDisplay.getMetrics(metrics);

        //拼接
        Canvas canvas = new Canvas(screenshot);
        canvas.drawBitmap(content, (layout.getWidth() - content.getWidth()) / 2, (layout.getHeight() - content.getHeight()) / 2, new Paint());
        canvas.drawBitmap(layout, 0, 0, new Paint());
        canvas.save();
        canvas.restore();

        OutputStream fout = null;
        try {
            fout = new FileOutputStream(imgFile);
            screenshot.compress(Bitmap.CompressFormat.PNG, 70, fout);
            fout.flush();
            fout.close();

            return imgFile.getAbsolutePath();
        } catch (FileNotFoundException e) {
            Logger.d(TAG, "FileNotFoundException");
            e.printStackTrace();
            return null;
        } catch (IOException e) {
            Logger.d(TAG, "IOException");
            e.printStackTrace();
            return null;
        }
    }

    public Bitmap convertViewToBitmap(View view) {
        Bitmap bitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        view.draw(canvas);
        return bitmap;
    }
上一篇 下一篇

猜你喜欢

热点阅读