尝试拍摄布局的屏幕截图,但它显示为空白图像

时间:2020-06-12 18:43:23

标签: java android android-studio

我的活动中有两个布局:顶部是线性布局,底部是约束布局。我只想截取线性布局的屏幕截图,但是由于某些原因,它会一直输出空白图像。

当我尝试使用getRootView()截取整个活动的屏幕截图时,效果很好。只是当我尝试使用特定布局时,我才遇到问题。

这是我的代码。我给了布局id=screenshotView

package com.example.transfergame;

public class ViewPlayerHistoryContents extends AppCompatActivity {

    public Bitmap takeScreenshot() {
        //View rootView = findViewById(android.R.id.content).getRootView();
        View rootView = findViewById(R.id.screenshotView);
        rootView.setDrawingCacheEnabled(true);
        return rootView.getDrawingCache();
    }

    public void saveBitmap(Bitmap bitmap) {
        imagePath = new File(Environment.getExternalStorageDirectory() + "/screenshot.png");
        FileOutputStream fos;
        try {
            fos = new FileOutputStream(imagePath);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();
        } catch (FileNotFoundException e) {
            Log.e("GREC", e.getMessage(), e);
        } catch (IOException e) {
            Log.e("GREC", e.getMessage(), e);
        }
    }

    private void shareIt() {

        Uri imageUri = FileProvider.getUriForFile(
            ViewPlayerHistoryContents.this,
            "com.example.transfergame.provider", //(use your app signature + ".provider" )
            imagePath);
        Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
        sharingIntent.setType("image/*");
        String shareBody = "Can you guess who this is?";
        sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareBody);
        sharingIntent.putExtra(Intent.EXTRA_STREAM, imagePath);

        startActivity(Intent.createChooser(sharingIntent, "Share via"));
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.view_player_history);

        shareButton = findViewById(R.id.shareButton);

        shareButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Bitmap bitmap = takeScreenshot();
                saveBitmap(bitmap);
                shareIt();

            }
        });

    }
}

为什么我的屏幕截图中只有空白屏幕?

0 个答案:

没有答案