Android View截屏长图拼接(NestedScrollView)

Android页面View截图(分享、保存相册)

Android View 截屏上下拼接  

NestedScrollView只有一个childView,虽然没有全部显示在界面上,但是已经全部渲染绘制,因此我们只需要获取NestedScrollView的高度,就可以直接 调用NestedScrollView.draw(canvas)来完成截图。剩下就是拼接两个Bitmap了。具体看代码逻辑。

  /**
     * 拼接长图,通过topNestedScrollView + bottomView实现 NestedScrollView截长图并拼接bottomView
     *
     * @param nestedScrollView
     * @param bottomView
     * @return
     */
    public static Bitmap mergeBitmapTopBottomByScrollView(NestedScrollView nestedScrollView, View bottomView) {
        int topW = nestedScrollView.getWidth();
        int topH = 0;
        int bottomW = bottomView.getWidth();
        int bottomH = bottomView.getHeight();
        for (int i = 0; i < nestedScrollView.getChildCount(); i++) {
            topH += nestedScrollView.getChildAt(i).getHeight();
            nestedScrollView.getChildAt(i).setBackgroundColor(ContextCompat.getColor(nestedScrollView.getContext(), R.color.common_color_bg_f1f3f5_color));
        }

        Bitmap topBitmap = Bitmap.createBitmap(topW, topH, Bitmap.Config.RGB_565);
        Canvas topCanvas = new Canvas(topBitmap);
        topCanvas.drawColor(Color.WHITE);
        nestedScrollView.layout(0, 0, topW, topH);
        nestedScrollView.draw(topCanvas);


        Bitmap bottomBitmap = Bitmap.createBitmap(bottomW, bottomH, Bitmap.Config.RGB_565);
        Canvas bottomCanvas = new Canvas(bottomBitmap);
        /** 如果不设置canvas画布为白色,则生成透明 */
        bottomCanvas.drawColor(Color.WHITE);
        bottomView.layout(0, 0, bottomW, bottomH);
        bottomView.draw(bottomCanvas);


        Bitmap bitmap = Bitmap.createBitmap(topW, topH + bottomH, Bitmap.Config.RGB_565);
        Canvas canvas = new Canvas(bitmap);


        Rect topRect = new Rect(0, 0, topW, topH);
        Rect bottomRect = new Rect(0, 0, bottomW, bottomH);

        Rect bottomDst = new Rect(0, topH, bottomW, topH + bottomH);

        canvas.drawBitmap(topBitmap, topRect, topRect, null);
        canvas.drawBitmap(bottomBitmap, bottomRect, bottomDst, null);
        topBitmap.recycle();
        bottomBitmap.recycle();
        topBitmap = null;
        bottomBitmap = null;
        return bitmap;
    }

你可能感兴趣的:(View,android)