Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Take screenshot with dialog

Tags:

android

I need to take screenshot programmatically of activity view. I have found a lot of answers how to do it, but there is not answer how to do it with opened dialog

like image 368
bylynka Avatar asked Jun 30 '13 18:06

bylynka


1 Answers

Ok this one is a little tricky. There is no direct way to do it as far as I know. Here is something that works. I tried to take individual shots and layer them.

Dialog dialog = // Dialog that is showing

View mainView = getSupportActivity().getWindow().getDecorView();
mainView = getSupportActivity().getWindow().getDecorView()
        .findViewById(android.R.id.content);
mainView.setDrawingCacheEnabled(true);
// This is the bitmap for the main activity
Bitmap bitmap = mainView.getDrawingCache();

View dialogView = dialog.getView();
int location[] = new int[2];
mainView.getLocationOnScreen(location);
int location2[] = new int[2];
dialogView.getLocationOnScreen(location2);

dialogView.setDrawingCacheEnabled(true);
// This is the bitmap for the dialog view
Bitmap bitmap2 = dialogView.getDrawingCache();

Canvas canvas = new Canvas(bitmap);
// Need to draw the dialogView into the right position
canvas.drawBitmap(bitmap2, location2[0] - location[0], location2[1] - location[1],
        new Paint());

String filename = // filename to save
File myPath = new File(filename);
FileOutputStream fos = null;
try {
    fos = new FileOutputStream(myPath);
    bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
    fos.flush();
    fos.close();
    Trace.d("Twitter", "The file path is " + myPath);
} catch (FileNotFoundException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} catch (Exception e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

I just tried this and it worked. Hope this helps. Let me know if it doesn't work.

like image 144
Aswin Rajendiran Avatar answered Sep 24 '22 07:09

Aswin Rajendiran