I Want to render a view to a Bitmap and save the bitmap. But i need to do that all in off screen.
I've tried this:
LayoutInflater inflater = getLayoutInflater();
View linearview = (View) findViewById(R.id.linearview);
linearview = inflater.inflate(R.layout.intro, null);
Bitmap bm = Bitmap.createBitmap( linearview.getMeasuredWidth(), linearview.getMeasuredHeight(), Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(bm);
linearview.layout(0, 0, linearview.getLayoutParams().width, linearview.getLayoutParams().height);
linearview.draw(c);
String extStorageDirectory = Environment.getExternalStorageState().toString();
extStorageDirectory = Environment.getExternalStorageDirectory().toString();
OutputStream outStream = null;
File file = new File(extStorageDirectory, "screen1.PNG");
try {
outStream = new FileOutputStream(file);
bm.compress(Bitmap.CompressFormat.PNG, 100, outStream);
outStream.flush();
outStream.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
EDIT: My app crash because the view doesnt have any width or height. ( the measure is a try to fix that )
And srry for the bad english.
The problem is here:
linearview = inflater.inflate(R.layout.intro, null);
You need to pass a parent layout, so it can be properly measured. I understand you do not want the view to be attached to the layout, but you can use a parent layout just for the measuring by using this other version of the method, passing false to attachToRoot.
public View inflate (int resource, ViewGroup root, boolean attachToRoot)
From the official documentation of the paramenters:
root : Optional view to be the parent of the generated hierarchy (if attachToRoot is true), or else simply an object that provides a set of LayoutParams values for root of the returned hierarchy (if attachToRoot is false.)
attachToRoot : Whether the inflated hierarchy should be attached to the root parameter? If false, root is only used to create the correct subclass of LayoutParams for the root view in the XML.
When in doubt you can always pass the app content as a parent layout:
findViewById(android.R.id.content);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With