Android View截屏长图拼接(NestedScrollView)

该代码段展示了如何在Android中对NestedScrollView和bottomView进行截图并拼接成长图。首先,获取NestedScrollView和bottomView的高度和宽度,然后分别创建Bitmap并绘制到Canvas上。最后,将这两个Bitmap拼接成一张新的Bitmap并回收原始Bitmap资源。

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

Android View 截屏上下拼接  

Android View截屏长图拼接(RecyclerView)

Android View截屏长图拼接(NestedScrollView)

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;
    }

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值