如何拍摄、裁剪和分享屏幕截图?

How to take,crop and share screenshot?

我有一个代码要获取,保存然后分享 Activity 的屏幕截图。我的问题是我只想取 activity 的中心,所以我添加了这段代码

private  Bitmap cropBitmap(Bitmap bitmap)  {
            Bitmap bm = Bitmap.createBitmap(bitmap, 10, 10,  500,  500);
            return bm;
        }

但它仍然是原始屏幕截图,请帮助我,我尝试了很多解决方案,但似乎我不知道如何应用这些解决方案,因为我在编码方面非常业余。所以我希望能帮助我,请根据我的代码给我正确的解决方案。非常非常感谢

    @Override
    public void onClick(View v) {
        Bitmap bitmap = takeScreenshot();
        cropBitmap(bitmap);
        saveBitmap(bitmap);
        shareIt();
    }


    public Bitmap takeScreenshot() {
        View v1 = getWindow().getDecorView().getRootView();
        v1.setDrawingCacheEnabled(true);
        Bitmap bitmap = Bitmap.createBitmap(v1.getDrawingCache());
        v1.setDrawingCacheEnabled(false);
        return bitmap;
    }

    private  Bitmap cropBitmap(Bitmap bitmap)  {
        Bitmap bm = Bitmap.createBitmap(bitmap, 10, 10,  500,  500);
        return bm;
    }

    private void saveBitmap(Bitmap bitmap) {
        imagePath = new File(Environment.getExternalStorageDirectory() + "/screenshot.png"); ////File imagePath
        FileOutputStream fos;
        try {
            fos = new FileOutputStream(imagePath);
            bitmap.compress(Bitmap.CompressFormat.PNG, 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 myUri = Uri.fromFile(imagePath);
        Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
        sharingIntent.setType("image/*");
        sharingIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        String shareBody = "My highest score with screen shot";
        sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "My Catch score");
        sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareBody);
        sharingIntent.putExtra(Intent.EXTRA_STREAM, myUri);

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


    displayResults();

这样试试:

Bitmap bitmap = takeScreenshot();
Bitmap bitmapCropped = cropBitmap(bitmap);
saveBitmap(bitmapCropped );