Take screenshot with dialog

前端 未结 5 1533
既然无缘
既然无缘 2021-01-02 03:59

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

5条回答
  •  南笙
    南笙 (楼主)
    2021-01-02 04:08

    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.

提交回复
热议问题