无法对 android 中布局的可见 + 不可见部分进行完整截图

Unable to take full screenshot of visible + invisible part of the layout in android

我想保存整个可滚动布局的屏幕截图,但它只捕获了屏幕上可见的部分。

这是我的整个布局。

这是捕获的屏幕截图:

截图代码如下:

private void takeScreenshot() {
    View v1 = getWindow().getDecorView().getRootView();;
    v1.setDrawingCacheEnabled(true);
    Bitmap bitmap = Bitmap.createBitmap(v1.getDrawingCache());
    v1.setDrawingCacheEnabled(false);
    saveScreenshot(bitmap,"filename");
}

public void saveScreenshot(Bitmap bitmap,String name) {
    String mPath = Environment.getExternalStorageDirectory().toString() + "/" + name + ".jpg";
    File imageFile = new File(mPath);
    Msg.log(mPath);
    try {
        FileOutputStream outputStream = new FileOutputStream(imageFile);
        int quality = 100;
        bitmap.compress(Bitmap.CompressFormat.JPEG, quality, outputStream);
        outputStream.flush();
        outputStream.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

使用下面的代码拍摄完整的滚动视图屏幕截图

    Bitmap bitmap = getBitmapFromView(scrollview, scrollview.getChildAt(0).getHeight(), scrollview.getChildAt(0).getWidth());

private Bitmap getBitmapFromView(View view, int height, int width) {
    Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(bitmap);
    Drawable bgDrawable = view.getBackground();
    if (bgDrawable != null)
        bgDrawable.draw(canvas);
    else
        canvas.drawColor(Color.WHITE);
    view.draw(canvas);
    return bitmap;
}

用上述代码 return bitmap;

的输出替换您的代码 saveScreenshot(bitmap,"filename");

示例:

https://programmingcode4life.blogspot.com/2016/10/convert-layout-view-to-image-and-store.html