Android 不可见View转Bitmap注意事项(ScrollView)

因为View不可见,所以直接调用转换 bitmap 的方法不可行,必须得先把View 绘制出来再去转换。

项目中使用的是ScrollView,所以绘制的方法如下:

val scrollView = view.findViewById<ScrollView>(R.id.scrollView)
scrollView.measure(
                View.MeasureSpec.makeMeasureSpec(0,View.MeasureSpec.UNSPECIFIED),
                View.MeasureSpec.makeMeasureSpec(0,View.MeasureSpec.UNSPECIFIED)
)
scrollView.layout(0,0,scrollView.measuredWidth,scrollView.measuredHeight)

然后再调用 ScrollView 的截图方法即可:

public static Bitmap snapshotByScrollView(final ScrollView scrollView, final Bitmap.Config config) {
        if (scrollView == null || config == null) return null;
        try {
            View view = scrollView.getChildAt(0);
            int width = view.getWidth();
            int height = view.getHeight();

            Bitmap bitmap = Bitmap.createBitmap(width, height, config);
            Canvas canvas = new Canvas(bitmap);
            canvas.drawColor(BACKGROUND_COLOR);
            scrollView.layout(0, 0, scrollView.getMeasuredWidth(),
                    scrollView.getMeasuredHeight());
            scrollView.draw(canvas);
            return bitmap;
        } catch (Exception e) {
            Log.i(TAG, "snapshotByScrollView exception:${e}");
        }
        return null;
    }
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容