I'm trying to take a screenshot of a layout that's in a different XML file, without showing it. So far I'm able to take a screenshot of the current activity:
From my current activity:
public void takeScreenshot(){
View view = getWindow().getDecorView().getRootView();
Bitmap bitmap = GLOBAL.viewToBitmap(view);
String filename = "screenshot";
String folder = "/Pictures";
Boolean result = GLOBAL.saveBitmap(bitmap, filename, folder);
String message;
if(result){
message = "Screenshot saved in folder " + folder;
}else{
message = "Error taking screenshot";
}
Toast.makeText(this, message, Toast.LENGTH_LONG).show();
}
From my global class:
public Bitmap viewToBitmap(View view)
{
Bitmap bitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(),
Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
Drawable bgDrawable = view.getBackground();
if (bgDrawable != null) {
bgDrawable.draw(canvas);
}
else {
canvas.drawColor(Color.WHITE);
}
view.draw(canvas);
return bitmap;
}
public Boolean saveBitmap(Bitmap bitmap, String filename, String folder)
{
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + folder);
myDir.mkdirs();
File file = new File(myDir, filename + ".png");
if (file.exists())
file.delete();
try {
FileOutputStream out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
Now I'm trying to change my takeScreenshot() method, like this:
public void takeScreenshot(){
LayoutInflater inflater;
inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.screenshot_layout, null);
Bitmap bitmap = GLOBAL.viewToBitmap(view);
String filename = "screenshot";
String folder = "/Pictures";
Boolean result = GLOBAL.saveBitmap(bitmap, filename, folder);
String message;
if(result){
message = "Screenshot saved in folder " + folder;
}else{
message = "Error taking screenshot";
}
Toast.makeText(this, message, Toast.LENGTH_LONG).show();
}
...but the app crashes in the first like of viewToBitmap(), and I get the following while debugging:
Caused by: java.lang.IllegalArgumentException: width and height must be > 0
I tried giving the root LinearLayout in my layout file a fixed height and width, and then "wrap_content" with some child elements having fixed dimensions, so the height and width should both be greater than 0. So how can I properly get the view for the layout?
Thanks in advance.