3

So, I have a Camera Preview (backed by a surface view) and has regular Android UI views laid as overlay over the preview. How do I take a simple screenshot of the displayed screen view.

I tried with MediaProjection and could not make it work (I am still figuring out why is it not working). But I would like to use MediaProjection only as the last option as it involves launching a new activity. I also read about this new API PixelCopy but not sure if it will work for a composited view (of surafceview and regular views) but still to figure out if that API will work for me.

Please note that I am attempting to take a screenshot of the screen when it is basically showing 2 windows and their respective surfaces compositing to provide the final display. Anybody having a sample code for this scenario or some pointer would be appreciated.

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
Dibzmania
  • 1,934
  • 1
  • 15
  • 32

2 Answers2

0

This may be helpful : Pass the view object to the function and it will capture the screenshot of that particular view.

public static String captureScreen(View v) {
        Toast.makeText(v.getContext(), "Generating Screenshot. Please wait..", Toast.LENGTH_LONG).show();
        // View v = activity.getWindow().getDecorView().getRootView();
        v.setDrawingCacheEnabled(true);
        Bitmap bmp = Bitmap.createBitmap(v.getDrawingCache());
        v.setDrawingCacheEnabled(false);
        try {
            File dir = new File(Environment.getExternalStorageDirectory() + "/myfolder");
            if (!dir.exists()) {
                dir.mkdirs();
            }
            File file = new File(dir, System.currentTimeMillis() + ".jpg");
            FileOutputStream fos = new FileOutputStream(file);
            bmp.compress(Bitmap.CompressFormat.JPEG, 90, fos);
            fos.flush();
            fos.close();
            return file.getAbsolutePath();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
0

can you try this library

https://github.com/Muddz/PixelShot

Main function of the library is this one.

private Bitmap getViewBitmap() {
            Bitmap bitmap;
            if (view instanceof TextureView) {
                bitmap = ((TextureView) view).getBitmap();
                Canvas canvas = new Canvas(bitmap);
                view.draw(canvas);
                canvas.setBitmap(null);
                return bitmap;
            } else {
                bitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.ARGB_8888);
                Canvas canvas = new Canvas(bitmap);
                view.draw(canvas);
                canvas.setBitmap(null);
                return bitmap;
            }
        }
nkalra0123
  • 2,281
  • 16
  • 17