I want to take a screenshot programmatically of a Fragment. The screenshot must include even the portion that is yet to be seen by the user, i.e. the unscrolled portion of the activity.
Method 1
I have referred to this question on StackOverflow and implemented this code:
public boolean takeScreenShot() {
Bitmap bitmap = getScreenBitmap();
return saveBitmap(bitmap); // function to save the screenshot as a JPEG on the device
}
public Bitmap getScreenBitmap() {
if (mFragment == null) return null; //mFragment is the Fragment whose screenshot I need
View v = mFragment.getView(); //getView returns the rootView of the Fragment
v.setDrawingCacheEnabled(true);
/*The line causing trouble: v.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED), MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));*/
v.layout(0, 0, v.getMeasuredWidth(), v.getMeasuredHeight());
Bitmap bitmap = Bitmap.createBitmap(v.getMeasuredWidth(), v.getMeasuredHeight(), Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(bitmap);
v.draw(c);
v.setDrawingCacheEnabled(false);
return bitmap;
}
If I execute the above code with the v.measure()
line commented, I get a regular screenshot (excluding the yet-to-be-scrolled portion).
If I remove the comment and execute, the app crashes and I get this error:
java.lang.IllegalArgumentException: width and height must be > 0
at android.graphics.Bitmap.createBitmap(Bitmap.java:810)
at android.graphics.Bitmap.createBitmap(Bitmap.java:789)
at android.graphics.Bitmap.createBitmap(Bitmap.java:756)
at com.company.mypackage.custom.MyTestActivity.getScreenBitmap(MyTestActivity.java:180)
Method 2
If I replace the createBitmap
line in the above code snippet with
Bitmap b = Bitmap.createBitmap(v.getDrawingCache());
I get a NullPointerException
at this line because v.getDrawingCache()
returns null.
Method 3
I have tried PGSSoft's scrollscreenshot tool and executed this command after downloading the necessary packages (I have checked that the device number for my emulator is 5, and that I am executing it in the correct directory)
java -cp scrollscreenshot-latest.jar com.pgssoft.scrollscreenshot.ScrollScreenShot -i 5
This gives me this error:
Error: Could not find or load main class com.pgssoft.scrollscreenshot.ScrollScreenShot
Could anyone guide me as to how to proceed?